typed_descriptors.attr

Descriptor class for attributes.

Attr

class Attr(type, /, validator=None, *, readonly=False, backed_by=None, use_dict=None, use_slots=None)[source]

Bases: DescriptorBase[T]

A descriptor class for attributes, supporting:

  • static type checking for the attribute value

  • runtime type checking of values assigned to the attribute

  • optional runtime validation of values assigned to the attribute

  • optional read-only restrictions on the attribute (set once)

See DescriptorBase for details on how the attribute value is stored in each instance.

final __get__(instance, _)[source]

If the descriptor is accessed on an instance, returns the value of the attribute on the given instance.

If the descriptor is accessed on the owner class, i.e. if instance is None, returns the Attr object.

Raises:

AttributeError – if the attribute is not defined, see is_defined_on.

Parameters:
Return type:

T | Self

__init__(type, /, validator=None, *, readonly=False, backed_by=None, use_dict=None, use_slots=None)[source]

Creates a new attribute with the given type and optional validator.

Parameters:
Raises:
  • TypeError – if the type is not a valid type

  • TypeError – if the validator is not callable

Return type:

None

final __set__(instance, value)[source]

Sets the value of the descriptor on the given instance.

Raises:
  • AttributeError – if the attribute is readonly and it already has a value assigned to it

  • TypeError – if the value has the wrong type

  • ValueError – if a custom validator is specified and the value is invalid

Parameters:
  • instance (Any) –

  • value (T) –

Return type:

None

final is_defined_on(instance)[source]

Wether the attribute is defined on the given instance.

Parameters:

instance (Any) –

Return type:

bool

property readonly

Whether the attribute is readonly.

Return type:

bool

static validator(validator_fun=None, /, *, readonly=False, backed_by=None, use_dict=None, use_slots=None)[source]

Decorator used to create an Attr from a validator function, optionally specifying a readonly modifier and a backing attribute.

It can be used directly, for mutable attributes with default backing attribute name:

class MyClass:

    @Attr.validator
    def x(self, value: Sequence[str]) -> bool:
        ''' Validator function for attribute 'C.x'. '''
        return 1 <= len(value) <= 3

It can be used by supplying readonly and backed_by values, for more general attributes:

class MyClass:

    @Attr.validator(readonly=True)
    def x(self, value: int|str) -> bool:
        ''' Validator function for readonly attribute 'C.x'. '''
        if isinstance(value, int):
            return value > 0
        return len(value) > 0

    @Attr.validator(backed_by='_w')
    def w(self, value: Sequence[int]) -> bool:
        ''' Validator function for mutable attribute 'C.w'. '''
        return len(value) in range(3)

    __slots__ = ("__x", "_w")
    #    default ^^^^^  ^^^^ custom
    #        backing attributes
Parameters:
Return type:

ValidatedAttrFactory | Attr[T]

property validator_fun

The custom validator function for the attribute, or None if no validator was specified.

There are two ways in which the validator can trigger an error:

  • By returning False: a ValueError is raised

  • By raising any exception as part of its body: the exception is caught as part of a try…except block, and a ValueError is raised from it (preserving the original error information).

In the second case, the validator should return True at the end, to signal that validation was successful.

Return type:

Optional[ValidatorFunction[T]]

SupportsBool

class SupportsBool(*args, **kwargs)[source]

Bases: Protocol

Structural types for things which can be converted to bool.

T_contra

T_contra = -T_contra

Contravariant type variable for generic values.

ValidatedAttrFactory

class ValidatedAttrFactory(*args, **kwargs)[source]

Bases: Protocol

Structural type for functions which create Attr instances from validator functions.

ValidatorFunction

class ValidatorFunction(*args, **kwargs)[source]

Bases: Protocol[T_contra]

Structural type for the validator function of a Attr.

validate_validator_fun

validate_validator_fun(validator_fun, /)[source]

Runtime validation for validator functions.

Raises:

TypeError – if the argument is not a validator function

Parameters:

validator_fun (ValidatorFunction[T]) –

Return type:

None

validator_fun_value_type

validator_fun_value_type(validator_fun, /)[source]

Returns the type annotation for the value argument of a validator function. Used by Attr.validator to infer the Attr type from the validator function type hints.

Raises:
  • TypeError – if the argument is not a validator function

  • ValueError – if the function doesn’t have an explicit annotation for its value argument type or its return type.

Parameters:

validator_fun (ValidatorFunction[T]) –

Return type:

Any