function v. method

danielx danielwong at berkeley.edu
Tue Jul 18 01:13:38 EDT 2006


At first I was going to post the following:

<!-- beginning of my original post -->

I just discovered the inspect module, which contains the isfunction and
ismethod functions. For some reason, I used to be under the impression
that Python methods are no different from Python functions. Naturally,
I wondered why both of these needed to exist (I also later discovered
the isroutine function). So I started to experiment at prompt. Here's
what I did:

>>> from inspect import *
>>> def dan(): pass
...
>>> ismethod(dan)
False
>>> isfunction(dan)
True
>>> class Foo:
... 	def meth(self): pass
...
>>> m = Foo.meth
>>> m
<unbound method Foo.meth>
>>> ismethod(m)
True
>>> Foo.func = dan    # <-- Appearantly, something magical happens here, because...
>>> Foo.func
<unbound method Foo.dan>
>>> f = Foo.func
>>> f is dan               # <-- things begins to look suprising here.
False
>>> ismethod(f)
True

Imagine my surprise. Why would Python do this?

<!-- end of my original post, with ending censored -->

but then I tried this:

>>> res = Foo.__dict__['func']
>>> res is dan
True

And it all started to make sense. The surprising thing turned out to be
not so surprising: When the expression Foo.func gets evaluated, we get
a method which is just a wrapper around dan. Therefore, f is not dan!

This is still a little bit of magic, which gets me thinking again about
the stuff I self-censored. Since the dot syntax does something special
and unexpected in my case, why not use some more dot-magic to implement
privates? Privates don't have to be entirely absent from Klass.__dict__
(which would make Python not introspective); they can just be invisible
when using the dot-syntax.

BTW, I am aware of Python's name mangling feature.




More information about the Python-list mailing list