Type safety in Python

ignoramus picture ignoramus · Sep 20, 2010 · Viewed 15.2k times · Source

I've defined a Vector class which has three property variables: x, y and z. Coordinates have to be real numbers, but there's nothing to stop one from doing the following:

>>> v = Vector(8, 7.3, -1)
>>> v.x = "foo"
>>> v.x
"foo"

I could implement "type safety" like this:

import numbers

class Vector:
    def __init__(self, x, y, z):
        self.setposition(x, y, z)

    def setposition(self, x, y, z):
        for i in (x, y, z):
            if not isinstance(i, numbers.Real):
                raise TypeError("Real coordinates only")

        self.__x = x
        self.__y = y
        self.__z = z

    @property
    def x(self):
        return self.__x

    @property
    def y(self):
        return self.__y

    @property
    def z(self):
        return self.__z

...but that seems un-Pythonic.

Suggestions?

Answer

knitti picture knitti · Sep 20, 2010

You have to ask yourself why you want to test type on setting these values. Just raise a TypeError in any calculation which happens to stumble over the wrong value type. Bonus: standard operations already do this.

>>> 3.0 / 'abc'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for /: 'float' and 'str'