Class

Accretive classes are similar to standard Python classes, but with the added property that once an attribute is set, it cannot be altered or removed. This makes them useful for defining constants or configurations that should remain immutable once defined.

>>> from accretive import Class

Initialization

Accretive classes can be defined using the Class metaclass. Attributes can be added during class definition.

>>> class Config( metaclass = Class ):
...     host = 'localhost'
...     port = 8080
>>> Config.host
'localhost'

Immutability

Existing attributes cannot be reassigned.

>>> Config.host = '127.0.0.1'
Traceback (most recent call last):
...
accretive.exceptions.AttributeImmutabilityError: Cannot reassign or delete existing attribute 'host'.

Or deleted.

>>> del Config.port
Traceback (most recent call last):
...
accretive.exceptions.AttributeImmutabilityError: Cannot reassign or delete existing attribute 'port'.

Attribute Assignment

However, new attributes can be assigned.

>>> Config.new_feature = 'enabled'
>>> Config.new_feature
'enabled'

Decorator Usage

Accretive classes can also use decorators to modify class behavior. Decorators can add new attributes, but cannot modify existing ones.

>>> def add_version( cls ):
...     cls.version = '1.0'
...     return cls
>>> class AppConfig( metaclass = Class, decorators = ( add_version, ) ):
...     name = 'MyApp'
>>> AppConfig.version
'1.0'
>>> AppConfig.name
'MyApp'
>>> AppConfig.name = 'NewApp'
Traceback (most recent call last):
...
accretive.exceptions.AttributeImmutabilityError: Cannot reassign or delete existing attribute 'name'.

Mutable Attributes

While accretive classes make attributes immutable by default after assignment, you can designate specific attributes as mutable using the mutables parameter. This is useful for attributes that need to be updated or removed throughout the class lifecycle.

>>> class Configuration( metaclass = Class, mutables = ( 'version', ) ):
...     name = 'MyApp'
...     version = '1.0.0'
...     release_date = '2025-01-01'

>>> # Standard immutable attributes behave as expected
>>> Configuration.name = 'NewApp'
Traceback (most recent call last):
...
accretive.exceptions.AttributeImmutabilityError: Cannot reassign or delete attribute 'name'.

>>> # Mutable attributes can be modified
>>> Configuration.version = '1.0.1'
>>> Configuration.version
'1.0.1'

>>> # Mutable attributes can also be deleted
>>> del Configuration.version
>>> hasattr( Configuration, 'version' )
False

>>> # New mutable attributes can be added later
>>> Configuration.version = '1.1.0'
>>> Configuration.version
'1.1.0'

Dynamic Docstring Assignment

Accretive classes support dynamic docstring assignment, allowing for computed docstrings to be set at class creation.

>>> class DocumentedConfig( metaclass = Class, docstring = 'Dynamic docstring' ):
...     ''' Static docstring '''
...     host = 'localhost'
>>> DocumentedConfig.__doc__
'Dynamic docstring'