Defining otherwise type#

In certain cases, it is required to be able to allow the “else case” when defining a particular attribute of a class. For instance, let us say our attribute should be a vector of size 3, but if it is not, a string should be allowed.

A class with imposed typesystem would be:

[1]:
import ubermagutil.typesystem as ts


@ts.typesystem(a=ts.Vector(size=3, otherwise=str))
class DecoratedClass:
    def __init__(self, a):
        self.a = a

Now, we can instantiate the class and pass the vector of length 3.

[2]:
dc = DecoratedClass(a=(0, 1, 2))
dc.a
[2]:
(0, 1, 2)

Because we also defined otheriwse parameter, we can also assign a string.

[3]:
dc.a = "Mihajlo Pupin"

However if we pass an integer or a size 2 tuple, an exception is raised:

[4]:
try:
    dc.a = 23
except TypeError:
    print("Exception raised.")
Exception raised.
[5]:
try:
    dc.a = (1, 2)
except ValueError:
    print("Exception raised.")
Exception raised.

Attempts to assign a new value to the attribute, did not affect its value.

[6]:
dc.a
[6]:
'Mihajlo Pupin'