On 2013-10-19 22:55, Ned Batchelder wrote:
On 10/19/13 5:44 PM, Peter Cacioppi wrote:
Is the following considered poor Python form?

class Foo (object) :
     _lazy = None
     def foo(self, x) :
         _lazy = _lazy or self.get_something(x)
     def get_something(self, x) :
         # doesn't really matter

I like this idiom for certain situations, just wondering if it will raise the
hackles of other Pythonistas.

I use this idiom sparingly, but sometimes it just fits the task at hand, I
hear Guidos voice saying "use the Force" in my ear, etc.

You present this as a choice between __init__ or a class attribute, but those
two things are very different.  Is your intent to have an instance attribute, or
a class attribute?  Lazily populated instance attributes are fine, I would do it
like this:

class Foo(object):
     def __init__(self):
         self._lazy = None

     def foo(self, x):
         if self._lazy is None:
             self._lazy = self.get_something(x)
         ...

I think he left some important characters out.

class Foo (object) :
    _lazy = None
    def foo(self, x) :
        self._lazy = self._lazy or self.get_something(x)
        # Use self._lazy for something

    def get_something(self, x) :
        # doesn't really matter

The main difference being that he doesn't initialize the instance attribute and just relies on the fallback to class attribute lookup. In my experience, using a static[1] class attribute as a default for an instance attribute is accepted practice, and one that gets touted as a positive feature of Python's namespace model when compared against other languages. That said, I have seen it more often in the past.

[1] In the general "unchanging" sense rather than the C++ "static" keyword 
sense.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to