Search code examples
pythonpep8

Type of variables in a class: best programming practices


I define a class as below:

import numpy as np

class Vector:
    def __init__(self, v):
        self.v = v

I can create an instance of the class by doing the following:

p1 = np.array([0.0, 0.0, 0.0])

v1 = Vector(p1)
v2 = Vector(3)

My intention is that Vector always contains a vector in the 3D space. But, what is the proper way in python to make sure Vector will always be a 3-component vector?


Solution

  • You can do this in two ways, which can be used simultaneously. First, at runtime:

    class Vector:
        def __init__(self, v):
            if not isinstance(v, np.ndarray) or v.shape != (3,):
                raise ValueError("vector must be 3-dimensional array")
            self.v = v
    

    Checking types like this is pretty much a standard convention in python. However, with Python 3.5+ the typing module was added, which allows for so called "type hints", which can get statically analyzed by your IDE or linter:

    class Vector:
        def __init__(self, v: np.ndarray[float, shape=(3,)]):
            self.v = v
    

    However, type hinting is not yet fully implemented for numpy (the above syntax is preliminary), see this tracking issue on GitHub.