How to determine if the variable is a function in Python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Question
00:35 Accepted answer (Score 18)
01:34 Answer 2 (Score 14)
02:19 Answer 3 (Score 9)
02:32 Answer 4 (Score 4)
03:00 Thank you
--
Full question
https://stackoverflow.com/questions/2459...
Accepted answer links:
[inspect.isfunction]: http://docs.python.org/library/inspect.h...
Answer 2 links:
[docs.python.org]: http://docs.python.org/library/inspect.h...
Answer 3 links:
[callable]: http://docs.python.org/library/functions...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #function
#avk47
ANSWER 1
Score 14
You may use inspect.isfunction(object). See: docs.python.org
That said, you should avoid using this technique in your day-to-day code. Sometimes you actually need to use reflection - for example, an MVC framework might need to load a class and inspect its members. But usually you should return/pass/deal with objects that have the same "interface". For example, do not return an object that may be an integer or a function - always return the same "type" of object so your code can be consistent.
ANSWER 2
Score 9
There is a callable function in python.
if callable(boda):
ANSWER 3
Score 4
Use callable(boda) to determine whether boda is callable or not.
Callable means here being a function, method or even a class. But since you want to distinguish only between variables and functions it should work nicely.
Your code would then look like:
boda = len # boda is the length function now
if callable(boda):
print "Boda is a function!"
else:
print "Boda is not a function!"
ANSWER 4
Score 2
>>> import types
>>> def f(): pass
...
>>> x = 0
>>> type(f) == types.FunctionType
True
>>> type(x) == types.FunctionType
False
That will check if it's a function. callable() will check if it's callable (that is, it has a __call__ method), so it will return true on a class as well as a function or method.