If you want to use the syntax
def function(a: int):
pass
mentioned by @SimeonVisser and you have python3.5, you can use the decorator I wrote
from typing import get_type_hints
def strict_types(f):
def type_checker(*args, **kwargs):
hints = get_type_hints(f)
all_args = kwargs.copy()
all_args.update(dict(zip(f.__code__.co_varnames, args)))
for key in all_args:
if key in hints:
if type(all_args[key]) != hints[key]:
raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))
return f(*args, **kwargs)
return type_checker
while defining functions like that
@strict_types
def concatenate_with_spam(text: str) -> str:
return text + 'spam'
and it will raise an exception if the argument passed to your function is of the wrong type.
Traceback (most recent call last):
File "strict_types.py", line 23, in <module>
concatenate_with_spam(1)
File "strict_types.py", line 13, in type_checker
raise Exception('Type of {} is {} and not {}'.format(key, type(all_args[key]), hints[key]))
Exception: Type of text is <class 'int'> and not <class 'str'>
Though I haven't implemented a way to check the type of what you return and this solution won't suit you if you want to check it too.
isinstance(some_variable, int)- Steven Rumbalski