PEP for an unrestricted __init__ ?!

holger krekel pyth at devel.trillke.net
Thu Apr 18 16:42:45 EDT 2002


I'd would like to know if anybody thinks it's
worthwile to start a formal PEP for an 
"unrestricted __init__". The guiding idea is to bring full
factory-pattern power to the __init__ constructor
of a class.

The factory pattern aims at decoupling object creation 
from the current declaration (data-layout) of an object. 
In c++, java or corba (or other interface/implementation-systems)
you often need factories because objects
are more or less defined by their method/data-layouts
and if you directly call the constructor you make
your calling code dependent on the current data-layout
but you only want it to be dependend on the 'interface'
- or in python's words - on the objects  'behaviour'.

In python each new instance of a class is created by
__init__  and this doesn't tie the calling code to 
a particular data layout. You don't need factories 
to be able to work with the behaviour of an object
that's how python works anyway.

But a separate factory object has an advantage
that python's __init__ does not offer:

for example a factory object can return the same instance 
for certain parameters.  e.g.  multiple calls to

    aFactory.create('123') 

might always return the same object. (This is often
used for persistent objects to transparently deserialize
an object from a database.)

It might be very interesting to extend the __init__ semantics
to offer the same flexibility. __init__ would then
be allowed to return something other[1] than the implicite 'self'.

for example you could write:

class a:
	def __init__(self, id):
		if id in cache.keys():
			return cache[id] # currently raises TypeError
		.... # really create the object
		cache[id]=self
	
i guess that by allowing an unrestricted 'return' statement 
we would have the same flexibility that (clumsy)
factories for other languanges provide. Note that caching
like promoted is only *one* possibility what factories 
can do[2]. 

After all factories and constructors are not orthogonal
concepts. On the contrary, factories often are just
overhead both for the user and the programmer of a class.
Especially if you have several connected objects (referencing
each other) factories often become a pain and somewhat tricky to do.

comments? 

regards,

	holger krekel


--
[1] For backward compatibility we might need to treat 
    'return None' as 'return self' because __init__ currently 
    seems to follow this rule. 

[2] I know that in this special case we might also
    use the "borg-pattern": 
    	self.__dict__ == cache[id].__dict__ 
    instead of the return statement.
    But then counterintuitively 

	    a('123')!=a('123')  is true

    which of course could be fixed but
    unneccesarily complicates matters...
    	






More information about the Python-list mailing list