How to determine if the variable is a function in Python?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 How To Determine If The Variable Is A Function In Python?
00:29 Answer 1 Score 9
00:38 Answer 2 Score 4
00:59 Answer 3 Score 2
01:19 Answer 4 Score 14
01:51 Thank you
--
Full question
https://stackoverflow.com/questions/2459...
--
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.