In article <11**********************@g4g2000hsf.googlegroups. com>,
Robert Dailey <rc******@gmail.comwrote:
Hi,
Is there a way to force a specific parameter in a function to be a
specific type? For example, say the first parameter in a function of
mine is required to be a string. If the user passes in an integer, I
want to notify them that they should pass in a string, not an integer.
At present, there isn't any built-in way to do this (see the recent
thread "PEP 3107 and stronger typing" for a long discussion).
However, you can use assert and isinstance() to check it manually:
def foo(a):
assert isinstance(a, str), "argument 'a' must be a string"
I wouldn't advocate getting carried away with this pattern since it
precludes your function from working with duck typing and defeats some
of the dynamic nature of Python. On the other hand, without such checks
the resulting exceptions from assuming an argument is one type when it
is another can be a bit misleading.
Dave