Simple type checking using property()

Posted on January 8, 2013

Python usually relies of duck typing for type safety, but from time to time it can be handy to enforce some type checking, particularly when new users are going to be using your objects. The following are three utility methods for applying type checking to class properties, using the new style object property() method.

The results are:

$ python tmp.py 
Got stored value = 1
Traceback (most recent call last):
  File "tmp.py", line 28, in <module>
    a1.a = "1"
  File "tmp.py", line 11, in setter_real
    if not isinstance(var, valid_types): raise TypeError("Not of required type: "+str(valid_types))
TypeError: Not of required type: <type 'int'>