Know if a object member is a method

L

Luca

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?
 
S

Steven D'Aprano

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:
True

In my opinion, that's the best way.


If you are sure that the method won't have side-effects or bugs:
.... 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:
True
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top