Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3: how to check if an object is a function? [duplicate]

Am I correct assuming that all functions (built-in or user-defined) belong to the same class, but that class doesn't seem to be bound to any variable by default?

How can I check that an object is a function?

I can do this I guess:

def is_function(x):
  def tmp()
    pass
  return type(x) is type(tmp)

It doesn't seem neat, and I'm not even 100% sure it's perfectly correct.

like image 786
max Avatar asked Nov 17 '10 07:11

max


People also ask

How do you check if an element appears twice in a list Python?

For this, we will use the count() method. The count() method, when invoked on a list, takes the element as input argument and returns the number of times the element is present in the list. For checking if the list contains duplicate elements, we will count the frequency of each element.

Is there a duplicate function in Python?

The duplicated() method returns a Series with True and False values that describe which rows in the DataFrame are duplicated and not. Use the subset parameter to specify if any columns should not be considered when looking for duplicates.


2 Answers

in python2:

callable(fn)

in python3:

isinstance(fn, collections.Callable)

as Callable is an Abstract Base Class, this is equivalent to:

hasattr(fn, '__call__')
like image 129
dan_waterworth Avatar answered Sep 16 '22 19:09

dan_waterworth


How can I check that an object is a function?

Isn't this same as checking for callables

hasattr(object, '__call__')

and also in python 2.x

callable(object) == True
like image 29
pyfunc Avatar answered Sep 20 '22 19:09

pyfunc