By sheer coincidence I happened to be thinking about that while waiting
at an airport today. Check out the Python function "new" below:
# module t
class C0():
def init(self):
self.att1 = 1
self.att2 = 2
self.att3 = 3
return self
class C1():
def init(self,(att1)):
self.att1 = att1
self.att2 = 2
self.att3 = 3
return self
class C2():
def init(self,(att1,att2)):
self.att1 = att1
self.att2 = att2
self.att3 = 3
return self
class C3():
def init(self,(att1,att2,att3)):
self.att1 = att1
self.att2 = att2
self.att3 = att3
return self
def new(args):
if type(args) = type(('a','dummy','tuple')):
Class = args[0]
Instance = Class()
return Class.init(Instance, args[1:])
# just 1 arg, presumably a class
return args().init()
This works pretty well as is (except ... see later):
>>> from t import *
>>> def dump(x): print x, x.att1, x.att2, x.att3
..
>>> dump( new(C0) )
<instance object at 61b90> 1 2 3
>>> dump( new(C2,[3,4],'cow') )
<instance object at 60210> [3, 4] cow 3
>>> dump( new(C3,'a','b',{'c': 1}) )
<instance object at 60470> a b {'c': 1}
I don't know why, but this just doesn't work as expected for the C1
case:
>>> a = new(C1,0)
>>> a.att1
(0,)
>>>
I.e., the argument list tuple does not get unpacked as I thought it
would. Similarly:
>>> a,(b) = (1,(2,)) # does not unpack
>>> a
1
>>> b
(2,)
>>> a,(b,) = (1,(2,)) # does unpack
>>> a
1
>>> b
2
>>>
But also
>>> def init(x,(y,)):
Parsing error: file <stdin>, line 1:
def init(x,(y,)):
^
Unhandled exception: run-time error: syntax error
>>>
so I can't repair it by changing the declaration of C1's init function
to make clear that the "2nd argument" really is a singleton tuple.
Whatever,
A) My installation of Python is known to suffer from problems that other
installations don't have (so don't believe the above unless it
happens to you too).
B) This kind of trick should be easier (more straightforward; more
uniform) when the argument-clumping semantics are changed as Guido
described in a later mailing.
C) When a user can program a solution this easily, the case for building
it into the language is weak. To the extent that the case for
building it into the language can still be made, I'd be more inclined
to see it as pointing at weakness in Python's facilities for
manipulating methods & functions in general (as opposed to weakness
in Python's class-initialization facilities specifically). That is,
better to go for a general facility than a specific one, and in this
case Python is at worst "almost there" already.
encouraging-y'all-to-think-of-a-built-in-"new"-as-a-personal-defeat<grin>-
ly y'rs - tim
Tim Peters Kendall Square Research Corp
tim@ksr.com, ksr!tim@uunet.uu.net