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)
        ...

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

Reply via email to