typed_descriptors.attr
Descriptor class for attributes.
Attr
- class Attr(type, /, validator=None, *, readonly=False, backed_by=None, use_dict=None, use_slots=None, typecheck=True)[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
DescriptorBasefor 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
instanceisNone, returns theAttrobject.- Raises:
AttributeError – if the attribute is not defined, see
is_defined_on.- Parameters:
- Return type:
- __init__(type, /, validator=None, *, readonly=False, backed_by=None, use_dict=None, use_slots=None, typecheck=True)[source]
Creates a new attribute with the given type and optional validator.
- Parameters:
ty – the type of the attribute
validator (
Optional[ValidatorFunction[T]]) – an optional validator function for the attributereadonly (
bool; default =False) – whether the attribute is read-onlytypecheck (
bool; default =True) – whether to perform dynamic typechecks (default: True)
- Raises:
- Return type:
- 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:
- Return type:
- static validator(validator_fun=None, /, *, readonly=False, backed_by=None, use_dict=None, use_slots=None, typecheck=True)[source]
Decorator used to create an
Attrfrom 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
readonlyandbacked_byvalues, 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
- property validator_fun
The custom validator function for the attribute, or
Noneif no validator was specified.There are two ways in which the validator can trigger an error:
By returning
False: aValueErroris raisedBy raising any exception as part of its body: the exception is caught as part of a try…except block, and a
ValueErroris raised from it (preserving the original error information).
In the second case, the validator should return
Trueat the end, to signal that validation was successful.- Return type:
SupportsBool
T_contra
- T_contra = -T_contra
Contravariant type variable for generic values.
ValidatedAttrFactory
ValidatorFunction
validate_validator_fun
validator_fun_value_type
- validator_fun_value_type(validator_fun, /)[source]
Returns the type annotation for the
valueargument of a validator function. Used byAttr.validatorto infer theAttrtype 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
valueargument type or its return type.
- Parameters:
validator_fun (
ValidatorFunction[T])- Return type: