Don't check types, check actions. You don't actually care if it's a function (it might be a class instance with a __call__ method, for example) - you just care if it can be called. So use callable(f).
How to check for a function type in Python? - Stack Overflow
Do type hints/strict argument type checking works in Python?
Python type checking for functions - Stack Overflow
What's the canonical way to check for type in Python? - Stack Overflow
Don't check types, check actions. You don't actually care if it's a function (it might be a class instance with a __call__ method, for example) - you just care if it can be called. So use callable(f).
Because function isn't a built-in type, a NameError is raised. If you want to check whether something is a function, use hasattr:
>>> hasattr(f, '__call__')
True
Or you can use isinstance():
>>> from collections import Callable
>>> isinstance(f, Callable)
True
>>> isinstance(map, Callable)
True
I am trying the following code and it does not fail. Is there any special flag/annotation to enable type checking?
def test_type_hints(text: str): # accept strings only
print(text)
test_type_hints(5.2) # should fail (float instead of str)Basically, what I would like to achieve is:
def test_type_hints(text: str):
assert type(text) == str # <---------------
print(text)
test_type_hints(5.2)Use isinstance to check if o is an instance of str or any subclass of str:
if isinstance(o, str):
To check if the type of o is exactly str, excluding subclasses of str:
if type(o) is str:
See Built-in Functions in the Python Library Reference for relevant information.
Checking for strings in Python 2
For Python 2, this is a better way to check if o is a string:
if isinstance(o, basestring):
because this will also catch Unicode strings. unicode is not a subclass of str; both str and unicode are subclasses of basestring. In Python 3, basestring no longer exists since there's a strict separation of strings (str) and binary data (bytes).
Alternatively, isinstance accepts a tuple of classes. This will return True if o is an instance of any subclass of any of (str, unicode):
if isinstance(o, (str, unicode)):
The most Pythonic way to check the type of an object is... not to check it.
Since Python encourages Duck Typing, you should just try...except to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file, just try to use its .write() method!
Of course, sometimes these nice abstractions break down and isinstance(obj, cls) is what you need. But use sparingly.