type(foo) == function ?
Erik Max Francis
max at alcyone.com
Wed Nov 29 21:28:13 CET 2006
Tom Plunket wrote:
> I'd like to figure out if a given parameter is a function or not.
> <type 'int'>
>>>> type(1) == int
>>>> def foo():
> ... pass
> <type 'function'>
>>>> type(foo) == function
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> NameError: name 'function' is not defined
> Is there a way I can know if 'foo' is a function?
The type of a function is types.FunctionType:
>>> import types
>>> def f(): pass
>>> type(f) is types.FunctionType
However, this doesn't take into account methods (MethodType and
UnboundMethodType). In dynamically-typed languages in general, explicit
typechecks are not a good idea, since they often preclude user-defined
objects from being used. Instead, try performing the call and catch the
>>> f = 'asdf'
... except TypeError:
... print "oops, f is not callable"
oops, f is not callable
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
There are not fifty ways of fighting, there is only one: to be the
conqueror. -- Andrew Malraux, 1937
More information about the Python-list