Typed#
- class ubermagutil.typesystem.Typed(name=None, **kwargs)#
Descriptor allowing setting attributes only with values of a certain type.
- Parameters:
expected_type (type) – Allowed type of value.
allow_none (bool) – If
True
, the value can be set withNone
.
- Raises:
TypeError – If
type(value) != expected_type
.
Example
Usage of
Typed
descriptor.
>>> import ubermagutil.typesystem as ts ... >>> @ts.typesystem(myattribute=ts.Typed(expected_type=str)) ... class DecoratedClass: ... def __init__(self, myattribute): ... self.myattribute = myattribute ... >>> dc = DecoratedClass(myattribute='Nikola Tesla') >>> dc.myattribute 'Nikola Tesla' >>> dc.myattribute = 'Mihajlo Pupin' # valid set >>> dc.myattribute 'Mihajlo Pupin' >>> dc.myattribute = 3.14 # invalid set Traceback (most recent call last): ... TypeError: ...
Note
This class was derived from
ubermagutil.typesystem.Descriptor
and inherits its functionality.See also
Methods
__delete__
Deleting the decorated class attribute is never allowed and
AttributeError
is raised.__dir__
Default dir() implementation.
__eq__
Return self==value.
__repr__
Return repr(self).
If
self.const=True
, changing the value of a decorated class attribute after the initial set is not allowed.- __set__(instance, value)#
If
self.const=True
, changing the value of a decorated class attribute after the initial set is not allowed.- Raises:
AttributeError – If changing the value of a decorated class attribute is attempted.
Example
Changing the value of a constant decorated class attribute.
>>> import ubermagutil.typesystem as ts ... >>> @ts.typesystem(myattribute=ts.Descriptor(const=True)) ... class DecoratedClass: ... def __init__(self, myattribute): ... self.myattribute = myattribute ... >>> dc = DecoratedClass(myattribute="John Doe") >>> dc.myattribute 'John Doe' >>> dc.myattribute = 'Jane Doe' Traceback (most recent call last): ... AttributeError: ...