[Python-Dev] ConfigParser shootout, preliminary entry
Bob Ippolito
bob at redivi.com
Mon Oct 18 21:52:03 CEST 2004
On Oct 18, 2004, at 15:20, Josiah Carlson wrote:
>>> I think the syntax looks good, but as per a thread in python-list,
>>> you
>>> cannot discover the order of class variables by any solution
>>> (metaclass
>>> or otherwise), due to the fact that they become part of the class
>>> dictionary; which is arbitrarily unordered.
>>>
>>> If ordering is important to a user, one could have an optional
>>> __order__
>>> attribute that gives the list of items in-order.
>>
>> That's not quite true. TypedAttribute instances and iniSection's
>> __new__ could have serial numbers.
>
>
> 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')
print ''.join([k for k,v in MyContainer.sorted])
python
-bob
More information about the Python-Dev
mailing list