type(foo) == function ?
Erik Max Francis
max at alcyone.com
Wed Nov 29 15:28:13 EST 2006
Hi Tom.
Tom Plunket wrote:
> I'd like to figure out if a given parameter is a function or not.
>
> E.g.
>
>>>> type(1)
> <type 'int'>
>>>> type(1) == int
> True
>
> implies:
>
>>>> def foo():
> ... pass
> ...
>>>> type(foo)
> <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
>>> types.FunctionType
<type 'function'>
>>> def f(): pass
...
>>> type(f)
<type 'function'>
>>> type(f) is types.FunctionType
True
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
resulting TypeError:
>>> f = 'asdf'
>>> try:
... f()
... 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
mailing list