skipping __init__ and using exploiting a class member instead

Peter Cacioppi peter.cacioppi at gmail.com
Sat Oct 19 20:42:39 EDT 2013


To be clear, my original post had a goof. 

So my original, de-goofed, idiom was


class Foo (object) :
    _lazy = None
    def foo(self, x) :
        self._lazy = self._lazy or self.get_something(x)
    def get_something(self, x) :
        # doesn't really matter, so long as it returns truthy result

and the new, improved idiom is 

class Foo (object) :
    def foo(self, x) :
        self._lazy = getattr(self, "_lazy", None) or self._get_something(x)
    def _get_something(self, x) :    
        # doesn't really matter, so long as it returns truthy result

I was laboring under some misconception that there was Python magic that allowed __init__ and only __init__ to add class attributes by setting their values. Good to know this piece of magic isn't part of Python, and thus lazy eval can be handled more cleanly than I originally thought. 

In other words, "Guido was here".

Thanks again




More information about the Python-list mailing list