Alex Rivera | Logout

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

Asked 2010-11-17T07:23:41.520
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.

Edit
Report

1 Answer

3

You can do:

def is_function(x):
    import types
    return isinstance(x, types.FunctionType) \
        or isinstance(x, types.BuiltinFunctionType)
answered 2010-11-17T07:25:24.657

Your Answer