Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for a function type in Python?

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?

like image 552
kramer65 Avatar asked Jul 12 '13 10:07

kramer65


People also ask

Is there a function type in Python?

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.

How do you check if a variable is of a certain type Python?

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.

What does type () mean in Python?

Python type() The type() function either returns the type of the object or returns a new type object based on the arguments passed.

How do you check if a variable is of a type?

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 .


1 Answers

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).

like image 100
Daniel Roseman Avatar answered Oct 10 '22 03:10

Daniel Roseman