I have a variable, x
, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'function' is not defined
The reason I picked that is because
>>> type(x) <type 'function'>
So to be specific you will have to use isinstance(f, (types. FunctionType, types. BuiltinFunctionType)). And of course if you strictly want just functions, not callables nor methods.
To check if a variable is of type function, use the typeof operator, e.g. typeof myVariable === 'function' . The typeof operator returns a string that indicates the type of the value. If the type of the variable is a function, a string containing the word function is returned.
Find Methods of a Python Object Using the dir Method The first method to find the methods is to use the dir() function. This function takes an object as an argument and returns a list of attributes and methods of that object. From the output, we can observe that it has returned all of the methods of the object.
Syntax of the Python type() function 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.
If this is for Python 2.x or for Python 3.2+, you can use callable()
. It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:
callable(obj)
If this is for Python 3.x but before 3.2, check if the object has a __call__
attribute. You can do this with:
hasattr(obj, '__call__')
The oft-suggested types.FunctionTypes
or inspect.isfunction
approach (both do the exact same thing) comes with a number of caveats. It returns False
for non-Python functions. Most builtin functions, for example, are implemented in C and not Python, so they return False
:
>>> isinstance(open, types.FunctionType) False >>> callable(open) True
so types.FunctionType
might give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.
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