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 of numbers.Real (e.g. int or float).

  • 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 neither numbers.Real nor expected_type (if passed).

  • ValueError – If value < 0 and unsigned=True is passed or value <= 0 and positive=True is passed.

Example

  1. 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

Descriptor


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).

__set__

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

  1. 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: ...