On Mar 17, 4:12 am, Bruno Desthuilliers <bruno.
42.desthuilli...@websiteburo.invalid> wrote:
> Patrick Maupin a écrit :
>
> > On Mar 16, 1:59 pm, Jason Tackaberry <t...@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.
>
> A possible optimization would be a simple memoization on first access.

I do agree that memoization on access is a good pattern, and I use it
frequently.  I don't know if I would want the interpreter
automagically doing that for everything, though -- it would require
some thought to figure out what the overhead cost is for the things
that are only used once.

Usually, I will have a slight naming difference for the things I want
memoized, to get the memoization code to run.  For example, if you add
an underbar in front of everything you want memoized:

class foo(object):

    def _bar(self):
        pass

    def __getattr__(self, aname):
        if aname.startswith('_'):
            raise AttributeError
        value = getattr(self, '_' + aname)
        self.aname = value
        return value

obj = foo()

So then the first time you look up obj.bar, it builds the bound
method, and on subsequent accesses it just returns the previously
bound method.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to