Since functions are values in Python, how do I determine if the variable is a function?
For example:
boda = len # boda is the length function now
if ?is_var_function(boda)?:
print "Boda is a function!"
else:
print "Boda is not a function!"
Here hypothetical ?is_var_function(x)?
should return true if x
is a callable function, and false if it is not.
Python doesn't have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object.
The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
Use the typeof operator to check if an object contains a function, e.g. typeof obj. sum === 'function' . The typeof operator returns a string that indicates the type of the value. For functions, the operator returns a string containing the word function.
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.
The callable
built-in mentioned in other answers doesn't answer your question as posed, because it also returns True
, besides functions, for methods, classes, instances of classes which define a __call__
method. If your question's title and text are wrong, and you don't care if something is in fact a function but only if it's callable, then use that builtin. But the best answer to your question as posed is: import the inspect
method of Python's standard library, and use inspect.isfunction. (There are other, lower-abstraction ways, but it's always a good idea to use functionality of the inspect
module for introspection when it's there, in preference to lower-level approaches: inspect
helps keep your code concise, clear, robust, and future-proof).
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