to pass self or not to pass self

Patrick Maupin pmaupin at gmail.com
Wed Mar 17 01:35:03 EDT 2010


On Mar 16, 1:59 pm, Jason Tackaberry <t... at urandom.ca> wrote:
> Why not create the bound methods at instantiation time, rather than
> using the descriptor protocol which has the overhead of creating a new
> bound method each time the method attribute is accessed?

Well, for one thing, Python classes are open.  They can be added to at
any time.  For another thing, you might not ever use most of the
methods of an instance, so it would be a huge waste to create those.

Also, this area has been optimized for normal usage patterns quite
heavily, to the point where attempted "optimizations" can lead to
results that are, on the surface, quite counterintuitive.

For example, if you want to take the length of a lot of different
strings, you might think you could save time by binding a local
variable to str.__len__ and using that on the strings.  Here is an
example:

>>> def a(s, count, lenfunc):
...     for i in xrange(count):
...        z = lenfunc(s)
...
>>> a('abcdef', 100000000, len)
>>> a('abcdef', 100000000, str.__len__)

Running cPython 2.6 on my machine, len() runs about 3 times faster
than str.__len__().  The overhead of checking that an object is usable
with a particular class method far outweighs the cost of creating the
bound method!

So, one thought for the OP.  Whenever I have a dictionary that
contains class methods in it, if I'm going to use it heavily, I often
recode it to create the dictionary at object creation time with bound
methods in it.

Regards,
Pat



More information about the Python-list mailing list