Published: Wed 18 May 2016
in Python
Type checking in Python?
Since Python is a dynamically typed language, it doesn't offer type checking out of the box. There are workarounds around this though. One that I use in my projects is the following:
def T(val, t):
assert type(val) == t, '(%s) %s != %s' % (str(val), type(val), t)
Here's an example of how to use this:
def sum(a, b):
T(a, int)
T(b, int)
return a + b
Let's say that you call the function incorrectly, like this:
a = "hello"
b = 5
s = sum(a, b)
You'll get the following exception:
>>> sum(a, b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in sum
File "<stdin>", line 2, in T
AssertionError: (hello) <type 'str'> != <type 'int'>
So that's it - pretty simple. I use the T
function every once in a while, to guard against type errors.