PEP for an unrestricted __init__ ?!

holger krekel pyth at devel.trillke.net
Thu Apr 18 23:05:35 EDT 2002


On Thu, Apr 18, 2002 at 10:00:36PM +0000, Terry Reedy wrote:
> To expand on JR's answer and identify your misconceptions:
> 
> > In python each new instance of a class is created by __init__
> 
> No, instance is first created by internal default constructor or
> new-style user-supplied equivalent __new__().  Then __init__ is
> called, if it exists, with new instance as first arg to initialize
> that new instance.

thanks! i also realized this after reading PEP 253. i certainly
haven't understood this PEP completly, though :-)
 
> > __init__ would then
> > be allowed to return something other[1] than the implicite 'self'.
> 
> > [1] For backward compatibility we might need to treat
> >     'return None' as 'return self' because __init__ currently
> >     seems to follow this rule.
> 
> __init__ is called as a proceedure -- *any* return is ignored

actually a TypeError is raised if you don't return None. At least
in python2.2rc2 this is so.

The question for me still is if relaxing the restrictions with 
__init__  or rather __new__ (which seems to have the same restrictions) 
would bring the benefit of making constructors as flexible as a separate
factory object could be. This way the class would have the control 
over what it actually means to 'create an object with the class's behaviour'. 
Two quick examples of uses:

- wrapping the instance with a generic cache class
  (see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 for
  an example).

- returning a proxy class which actually performs remote network
  calls to the 'real' instance.

the point here is that the calling side of the constructor
doesn't need to *know* about what the factory-like constructor
thinks is appropriate but can continue to rely on 'expected behaviour'. 

Of course you can put this functionality into a separate factory
object. But my whole point is that python already obsoletes
reasons for having factories (like in java or c++). And that it might
be interesting to introduce even more flexibility for constructors
so that the classical redundancies of Factories and Constructors
can be eliminated for many cases.

regards,

    holger





More information about the Python-list mailing list