Skip to main content

A collection of useful mixin classes for Python that add common functionality like dictionary-style access, attribute handling, and iteration support

Project description

xtclass

PyPI version Python versions License: MIT Code style: ruff

A collection of useful mixin classes for Python that add common functionality like dictionary-style access, attribute handling, and iteration support.

Features

  • Dictionary-style access: Use obj[key] syntax to get/set/delete attributes
  • Enhanced attribute handling: Safe attribute access with default values
  • Iteration support: Iterate over object attributes like a dictionary
  • Smart string representation: Automatic __repr__ with all attributes
  • Metaclass magic: Dynamic mixin application based on class attributes
  • Utility classes: Specialized classes like SetOnceDict for specific use cases

Installation

pip install xtclass

Quick Start

Basic Usage

from xtclass import BaseCls

class Person(BaseCls):
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create an instance
person = Person("Alice", 30)

# Dictionary-style access
print(person["name"])  # Alice
person["city"] = "New York"
print(person["city"])  # New York

# Attribute access with defaults
print(person.nonexistent)  # None (no AttributeError)

# Iteration
for key, value in person:
    print(f"{key}: {value}")

# Enhanced string representation
print(person)  # Person(name='Alice', age=30, city='New York')

Using Individual Mixins

from xtclass import ItemMixin, AttrMixin, IterMixin

class MyClass(ItemMixin, AttrMixin, IterMixin):
    def __init__(self):
        self.data = "test"

obj = MyClass()
obj["key"] = "value"  # Dictionary-style access
print(obj.nonexistent)  # None (safe attribute access)
for k, v in obj:  # Iteration
    print(f"{k}: {v}")

Using the Metaclass

from xtclass import MixinClsParent

class MyClass(MixinClsParent):
    MixinItem = True    # Enable dictionary-style access
    MixinAttr = True    # Enable safe attribute access
    MixinIter = True    # Enable iteration
    MixinRepr = True    # Enable enhanced string representation

    def __init__(self):
        self.value = 42

obj = MyClass()
print(obj["value"])  # 42
print(obj)  # MyClass(value=42)

Utility Classes

from xtclass import SetOnceDict

# Create a dictionary that only allows setting values once
sod = SetOnceDict()
sod["key"] = "value"
sod["key"] = "new_value"  # This won't change the value
print(sod["key"])  # "value"

API Reference

Mixin Classes

ItemMixin

Provides dictionary-style access (obj[key]) for getting, setting, and deleting attributes.

AttrMixin

Provides safe attribute access that returns None for non-existent attributes instead of raising AttributeError.

IterMixin

Makes objects iterable, allowing you to iterate over their attributes.

ReprMixin

Provides enhanced string representation showing all object attributes.

BaseCls

A convenience class that combines all common mixins (AttrMixin, ItemMixin, IterMixin, ReprMixin).

Metaclass

MixinClsMeta

A metaclass that automatically applies mixins based on class attributes:

  • MixinItem = True: Apply ItemMixin
  • MixinAttr = True: Apply AttrMixin
  • MixinIter = True: Apply IterMixin
  • MixinRepr = True: Apply ReprMixin

MixinClsParent

A base class that uses MixinClsMeta for easy mixin application.

Utility Classes

SetOnceDict

A dictionary-like class that only allows setting values once per key.

Examples

Configuration Object

from xtclass import BaseCls

class Config(BaseCls):
    def __init__(self):
        self.debug = False
        self.timeout = 30

config = Config()

# Load from dictionary
config_data = {"debug": True, "host": "localhost"}
for key, value in config_data.items():
    config[key] = value

print(config)  # Config(debug=True, timeout=30, host='localhost')

Data Container

from xtclass import ItemMixin, IterMixin

class DataContainer(ItemMixin, IterMixin):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            self[key] = value

data = DataContainer(name="test", value=123)
print(dict(data))  # {'name': 'test', 'value': 123}

Development

Setup

git clone https://github.com/sandorn/xtclass.git
cd xtclass
pip install -e .

Testing

# Run tests
just test

# Run all quality checks
just qa

# Run tests with coverage
just coverage

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Run quality checks: just qa
  6. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Credits

This package was created with Cookiecutter and the audreyfeldroy/cookiecutter-pypackage project template.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xtclass-0.1.0.tar.gz (14.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

xtclass-0.1.0-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file xtclass-0.1.0.tar.gz.

File metadata

  • Download URL: xtclass-0.1.0.tar.gz
  • Upload date:
  • Size: 14.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for xtclass-0.1.0.tar.gz
Algorithm Hash digest
SHA256 a867c7c025f3f4fcf759f0cec6ea537cfc9d75cc253602877c859739fa36ff97
MD5 683b340f2c6fb78ef649b69caf0c74cb
BLAKE2b-256 cf96b57886061f378926641d838eb25d27df251ee62f4e7de4dd5de5d16de274

See more details on using hashes here.

File details

Details for the file xtclass-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: xtclass-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 10.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for xtclass-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 15fb1fea58e07429ac11972f65937b85ed6e7ef4af388a4a8e8bd19176019361
MD5 32620f2b56a43ec2f0b884a1913cda6b
BLAKE2b-256 8f6b1497a7f953eb3b2d5d4ce5392802d842b1afc66857897e3f7d61d05a8cba

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page