Connecting Tech Pros Worldwide Help | Site Map

Know if a object member is a method

Luca
Guest
 
Posts: n/a
#1: Sep 1 '08
Hi all.

I think this is a newbie question... what is the best method to know
if a property of an object is a function?

I'm thinking something as

if type(obj.methodName)==???

Can someone help me?

--
-- luca
Steven D'Aprano
Guest
 
Posts: n/a
#2: Sep 1 '08

re: Know if a object member is a method


On Mon, 01 Sep 2008 10:43:25 +0200, Luca wrote:
Quote:
Hi all.
>
I think this is a newbie question... what is the best method to know if
a property of an object is a function?
>
I'm thinking something as
>
if type(obj.methodName)==???
>
Can someone help me?
That's not quite as easy as you might think. In my testing, calling
type(obj.methodName) can give any of the following:

<type 'instancemethod'>
<type 'function'>
<type 'builtin_function_or_method'>


There may be others as well.

Possibly all you really need is to check if the attribute is callable
without caring what type of method or function it is:
Quote:
Quote:
Quote:
>>callable(obj.methodName)
True

In my opinion, that's the best way.


If you are sure that the method won't have side-effects or bugs:
Quote:
Quote:
Quote:
>>try:
.... obj.method()
.... except:
.... print "Not a method"
....

(But how can you be sure?)


If you insist on an explicit test, try this:

import new
type(obj.methodName) == new.instancemethod


or alternatively:
Quote:
Quote:
Quote:
>>isinstance(obj.methodName, new.instancemethod)
True




--
Steven
Closed Thread