How to decide if a object is instancemethod?

C

Cosmia Luna

class Foo(object):
def bar(self):
return 'Something'

func = Foo().bar

if type(func) == <type 'instancemethod'>: # This should be always true
pass # do something here

What should type at <type 'instancemethod'>?

Thanks
Cosmia
 
J

Jon Clements

class Foo(object):
def bar(self):
return 'Something'

func = Foo().bar

if type(func) == <type 'instancemethod'>: # This should be always true
pass # do something here

What should type at <type 'instancemethod'>?

Thanks
Cosmia

import inspect
if inspect.ismethod(foo):
# ...

Will return True if foo is a bound method.

hth

Jon
 
S

Steven D'Aprano

But under what other conditions will it return True? The name suggests
that *any* method – static method, class method, bound method, unbound
method – will also result in True.

The documentation says only “instance methodâ€, though. Confusing :-(


Bound and unbound methods are instance methods. To be precise, the
"method" in "(un)bound method" stands for instance method, and the
difference between the two in Python 2.x is a flag on the method object.
(Unbound methods are gone in Python 3.)

Class and static methods are not instance methods. I suppose it is
conceivable that you could have an unbound class method in theory, but I
can't see any way to actually get one in practice.

In Python, and probably most languages, a bare, unadorned "method" is
implied to be an instance method; "instance method" is (possibly) a
retronym to distinguish them from other, newer(?), types of method.

http://en.wikipedia.org/wiki/Retronym
 
J

Jean-Michel Pichavant

Jon said:
import inspect
if inspect.ismethod(foo):
# ...

Will return True if foo is a bound method.

hth

Jon
another alternative :

import types

if type(func) == types.MethodType:
pass

or possibly better

if isinstance(func, types.MethodType):
pass


JM
 

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
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top