I've got a list of things, of which some can also be functions. If it is a function I would like to execute it. For this I do a type-check. This normally works for other types, like str, int or float. But for a function it doesn't seem to work:
>>> def f():
... pass
...
>>> type(f)
<type 'function'>
>>> if type(f) == function: print 'It is a function!!'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>>
Does anybody know how I can check for a function type?
Python has a lot of built-in functions. The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
Use the type() Function to Check Variable Type in Python To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.
Python type() The type() function either returns the type of the object or returns a new type object based on the arguments passed.
Use isinstance() to check if a variable is a certain type Call isinstance(variable, type) to check if variable is an instance of the class type .
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With