skipping __init__ and using exploiting a class member instead

Ned Batchelder ned at nedbatchelder.com
Sat Oct 19 17:55:57 EDT 2013


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.



More information about the Python-list mailing list