19

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.

2
  • 2
    There are also objects with a call method that can be called as a function. Commented Nov 17, 2010 at 7:30
  • 1
    All classes can be called as a function. Commented Nov 17, 2010 at 9:49

4 Answers 4

27

in python2:

callable(fn)

in python3:

isinstance(fn, collections.Callable)

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

hasattr(fn, '__call__')
Sign up to request clarification or add additional context in comments.

1 Comment

The callable function was first removed in Python 3.0 and then brought back in Python 3.2 - so you can also use it w/ Python 3 if using a recent version of the interpreter. See docs.python.org/3/library/… for more information.
5

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

1 Comment

it also applies to classes, but +1 anyway has it seems more in the logic of duck typing
3

You can do:

def is_function(x):
    import types
    return isinstance(x, types.FunctionType) \
        or isinstance(x, types.BuiltinFunctionType)

6 Comments

but does this also check if it is of the same class ?
@Version, what do you mean by if it is of the same class?
is on type objects, yikes. If you must use explicit typechecks, at least use isinstance(), and preferably ask the inspect module to do it instead.
Explicit "type(object) is SomeType" is error-prone and has been long-ago replaced with isinstance - learn the new and improved coding idioms!
@Thomas, @Paul, you're right, answer updated. Thanks for the heads-up :)
|
-4
try:
    magicVariable()
except TypeError as e:
    print( 'was no function' )

12 Comments

-1, you shouldn't have to execute the function to test it.
My code is not meant as a test. When you have a variable, the only reason why you would check if it is a function is because you want to use it. So instead of investing time in checking that beforehand, you should just use it as a function and handle the exception.
i +1'ed it because in the general case, I think you're right but there are definitely cases where one wants to know if one is dealing with a function without having any intent of executing it. Metaclasses and class decorators come to mind.
@poke: no, that is one reason. What if you want store the function? If you use this method it will be much more difficult to debug.
This doesn't work if the function raises a TypeError.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.