Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect whether a Python variable is a function?

Tags:

python

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'> 
like image 338
Daniel H Avatar asked Mar 09 '09 03:03

Daniel H


People also ask

How do you check if a variable is a function in Python?

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.

How do you know if a variable is a function?

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.

How do you check a function in Python?

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.

What does type () do in Python?

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.


1 Answers

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.

like image 112
John Feminella Avatar answered Oct 02 '22 08:10

John Feminella