Scalar#
- class ubermagutil.typesystem.Scalar(name=None, **kwargs)#
Descriptor allowing setting attributes only with scalars (
numbers.Real
).- Parameters:
expected_type (int or float type, optional) – Allowed type of
value
. It should be a subset ofnumbers.Real
(e.g.int
orfloat
).positive (bool, optional) – If
positive=True
, value must be positive (>0).unsigned (bool, optional) – If
unsigned=True
, value must be unsigned (>=0).otherwise (type) – This type would also be accepted if specified. It has priority over other descriptor specification.
- Raises:
TypeError – If
type(value)
is neithernumbers.Real
norexpected_type
(if passed).ValueError – If
value < 0
andunsigned=True
is passed orvalue <= 0
andpositive=True
is passed.
Example
Usage of
Scalar
descriptor for defining a positive integer.
>>> import ubermagutil.typesystem as ts ... >>> @ts.typesystem(myattribute=ts.Scalar(expected_type=int, positive=True)) ... class DecoratedClass: ... def __init__(self, myattribute): ... self.myattribute = myattribute ... >>> dc = DecoratedClass(myattribute=5) >>> dc.myattribute 5 >>> dc.myattribute = 10 # valid set >>> dc.myattribute 10 >>> dc.myattribute = 3.14 # invalid set Traceback (most recent call last): ... TypeError: ... >>> dc.myattribute = 0 # invalid set Traceback (most recent call last): ... ValueError: ... >>> dc.myattribute # the value was not affected by invalid sets 10
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: ...