
On Oct 18, 2004, at 17:39, <exarkun@divmod.com> wrote:
On Mon, 18 Oct 2004 15:52:03 -0400, Bob Ippolito <bob@redivi.com> wrote:
On Oct 18, 2004, at 15:20, Josiah Carlson wrote:
[snip]
I'm not saying that they can't be numbered, I'm saying that one cannot discover the ordering of assignment of attr1 and attr2 in the following:
class foo: attr1 = value1 attr2 = value2
If there is a mechanism for discovering the original ordering of those assignments, there are a group of users in c.l.py who would like to know, and Carlos' seemingly non-existant implementation could also use it.
That is true, but you do know that the expression value1 is evaluated before the expression value2, so it is possible to sort later for clever enough choices of value1 and value2. Since his proposed syntax invokes something for each attribute, then this trick can certainly be used.. here's a small demonstration:
from itertools import count
class Value(object): def __init__(self, value, serial=count()): self.serial = serial.next() self.value = value
class Container(object): class __metaclass__(type): def __new__(cls, name, bases, dct): sorted = filter(lambda (k,v): isinstance(v, Value), dct.iteritems()) sorted.sort(lambda (ka,va),(kb, vb): cmp(va.serial, vb.serial)) dct['sorted'] = sorted return type.__new__(cls, name, bases, dct)
class MyContainer(Container): p = Value(2) y = Value(0) t = Value(-1) h = Value(20) o = Value('x') n = Value('z')
This breaks down for the perfectly reasonable case of:
hostname = Value("foo")
class First(Container): port = Value(64) hostname = hostname username = Value("zoop")
class Second(Container): username = Value("pooz") hostname = hostname port = Value(24)
ie, it breaks down as soon as you try to re-use anything, which is quite surprising to the unsuspecting user, and pretty unfortunate even once you do understand why.
Yes, it breaks down in the general case if you do things like that. The answer is just to not do things like that. You can make Value instances raise an exception the second time they're attached to a class and tell the user to subclass Value instead if they want to provide some default values. -bob