Attributes

Core module for working with attributes. Defines two important classes AttributesMixin (attributes container) and Attribute. Also defining all different kinds of specific attributes.

When designing this library, there was a need to implement some kind of mechanism, that would allow following:

  • Easy definition of data entities and their attributes, including their type, default value, range and whether they are immutable or read-only. This should be done in as declarative and concise form as possible.

  • Validation and possible conversion of values when assigning to these attributes.

  • Possibility to initialize the whole entity either in one step (passing all the values to the __init__ method) or gradually by assigning one attribute at a time.

  • There must be a way to initialize the entity without any validation.

Because of these requirements, I decided to implement the attribute as a descriptor. It allows for concise and clean definition and we can specify any custom logic we want when assigning a value, while keeping simple dot notation (obj.attribute = 1).

AttributesMixin is just a container for these descriptors, containing all the methods to ease the usage of it’s subclasses.

exception attributes.AttributeNotSetError(name)

Raised when accessing an attribute that was not yet set.

Parameters

name (str) –

msg = 'You must set the `{}` parameter'
exception attributes.AttributesNotSetError(params)

Raised if there are some attributes that were not yet set when validating an AttributesMixin instance.

Parameters

params (List[str]) –

msg = 'You must set following parameters: {}'
exception attributes.ReadOnlyAccessError(name)

Raised when assigning value to a read-only attribute.

Parameters

name (str) –

msg = 'Attribute `{}` is read only'
exception attributes.ModifyImmutableError(name)

Raised when assigning value to an immutable attribute that already has some value set.

Parameters

name (str) –

msg = 'Attribute `{}` is immutable - once set, it cannot be changed.'
exception attributes.InvalidValueError(value, name, type_)

Raised if validation failed when assigning to an attribute.

Parameters
  • value (Any) –

  • name (str) –

  • type_ (Type) –

msg = 'Invalid value `{}` for attribute `{}` of type `{}`'
exception attributes.NotInChoicesError(value, name, choices)

Raised if value assigned to an attribute is not in specified range of values.

Parameters
  • value (Any) –

  • name (str) –

  • choices (Sequence[Any]) –

msg = 'Invalid value `{}` for attribute `{}`, expected one of `{}`'
class attributes.AttributesMixin(**kwargs)

Container for Attribute instances. This class should not be used directly, instead it should be subclassed and have some attributes defined.

Note that if you try to retrieve an attribute that was not yet set and it does not have any default value, an exception will be raised.

Example usage:

>>> class Foo(AttributesMixin):
...     some_attr = BoolAttribute(immutable=True)
...     bar = IntegerAttribute(choices=(1, 2))

# Passing attribute values when creating object
>>> foo = Foo(some_attr=False)
>>> foo.some_attr
False

>>> foo.some_attr = True
Traceback (most recent call last):
...
dsw_sdk.common.attributes.ModifyImmutableError: ...

>>> foo.bar
Traceback (most recent call last):
...
dsw_sdk.common.attributes.AttributeNotSetError: ...

>>> foo.bar = 1
>>> foo.bar = 'two'
Traceback (most recent call last):
...
dsw_sdk.common.attributes.InvalidValueError: ...

>>> foo.bar = 3
Traceback (most recent call last):
...
dsw_sdk.common.attributes.NotInChoicesError: ...

# Use `_update_attrs` to skip validations
of `read_only` and `immutable` flags
>>> foo._update_attrs(some_attr=True)
>>> foo.some_attr
True
Parameters

kwargs – All the attributes you want to set on this instance. Note that the attribute must be defined on the class, otherwise it won’t get assigned. Attributes passed as a dict in _update_attrs keyword argument skip validation of read_only and immutable flags.

property attr_names

List of all attributes names defined on this class and all of it’s superclasses.

Returns

names of all attributes

attrs()

Collects all attribute values set on this instance, including default values of attributes and returns them as dict (keys are the attributes names).

Returns

dict with attribute names and corresponding values

Return type

Dict[str, Any]

validate()

Validates if all attributes that are needed (i.e. they don’t have the nullable flag set) are set. If not, raises an exception.

Raises

AttributesNotSetError if there are some attributes needed to be set

to_json()

Converts the whole instance (it’s attributes) to JSON representation. Useful for serializing the instance’s state.

Returns

dict representation of all the attributes and their values

Return type

Dict[str, Any]

class attributes.Attribute(type_, **kwargs)

Class representing one attribute on the AttributesMixin classes.

It’s defined as a data descriptor, responsible for validating values when the assignment takes place.

For example usage, see AttributesMixin, as these two can’t be really used separately.

Parameters

type_ (Type) – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

to_json(value)

Returns JSON representation of given value for the self._type data type.

Parameters

value (Any) – value to be converted

Returns

JSON representation of the value

Return type

Any

value_repr(value)

Returns string representation of given value for the self._type data type.

Parameters

value (Any) – value to be represented as a string

Returns

string representing value

Return type

str

class attributes.StringAttribute(**kwargs)
Parameters

type_ – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.IntegerAttribute(**kwargs)
Parameters

type_ – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.FloatAttribute(**kwargs)
Parameters

type_ – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.BoolAttribute(**kwargs)
Parameters

type_ – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.ListAttribute(type_, **kwargs)
Parameters

type_ (Type) – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.DictAttribute(key_type, value_type, **kwargs)
Parameters
  • type_ – type of the attribute

  • key_type (Type) –

  • value_type (Type) –

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.DateTimeAttribute(**kwargs)
Parameters

type_ – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.ObjectAttribute(type_, **kwargs)
Parameters

type_ (TypingType[AttributesMixin]) – type of the attribute

Keyword arguments
  • default (Any): default value for the attribute

  • nullable (bool): whether None should be a valid value

  • read_only (bool): if set to True, assigning to this attribute will raise an exception

  • immutable (bool): if set to True, it’s possible to assign a value to this attribute only once; any other try will raise an exception

  • choices (Sequence[Any]): sequence defining range of possible values

class attributes.Alias(aliased_attr)
Parameters

aliased_attr (str) –