skipping __init__ and using exploiting a class member instead

Peter Cacioppi peter.cacioppi at gmail.com
Sun Oct 20 04:46:18 EDT 2013


> Why not simply have one, and use it to initialize your attributes, 
> even if it is to None? 

Think about it this way. None here really means "not yet initialized". It is a value that cannot occur naturally and thus functions as a not-initialized flag.

But for different contexts, this value could be almost anything. It might even be truthy.

So this, somewhat arbitrary, context sensitive value should be isolated as much as possible.  You don't want it popping up hither and yon, you want to type as infrequently as possible and localized it to as few methods as possible.

For example, look at this version of the idiom

class Foo (Bar) :
   def foo(self, x) :
      if (getattr(self, "_lazy", -1) < 0 ) :
          self._lazy = self._count_something(x)
      assert (self._lazy >= 0) # a negative count is a bug not a bad data entry
   def count_something(self, x) :
       # if it's really counting something, it will return a natural number

Now you really want that -1 in an  __init__ method instead of the foo method? Isn't that asking for trouble when somebody copies this and rewrites it? They could change the boolean expressions in foo (i.e. < 0 means compute it, >= sanity checks the result) but fail to change the proper flag for not-yet-computed (-1) if these things are in two different methods.

My way, it's all in one place. 

Good little idiom to ponder though. I like fussing over these things. Any good gambler develops clean habits to improve his odds, even if each act of hygiene changes the odds but slightly.  I wouldn't complain if a co-worker coded this your way, but I still think it is cleaner my way.




More information about the Python-list mailing list