Know if a object member is a method
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon Sep 1 05:35:37 EDT 2008
On Mon, 01 Sep 2008 10:52:10 +0200, Manuel Ebert wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi Luca,
>
> use type(something).__name__ , e.g.
>
> >>> def x():
> >>> pass
> >>> class C:
> >>> pass
> >>> c = C()
> >>> type(x).__name__ == 'function'
> True
> >> type(C).__name__ == 'classobj'
> True
> >> type(c).__name__ == 'instance'
> True
That's relatively fragile, since such names aren't reserved in any way.
It's easy to fool a name comparison check with an accidental name
collision:
>>> class function(object): # not a reserved name
... pass
...
>>> x = function()
>>> type(x).__name__
'function'
>>> x() # must be a function then...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'function' object is not callable
But not so easy to fool a type check:
>>> type(x) == new.function
False
Of course that's not bullet-proof either. I leave it as an exercise to
discover how you might break that piece of code.
--
Steven
More information about the Python-list
mailing list