This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author carsten.klein@axn-software.de
Recipients carsten.klein@axn-software.de
Date 2010-08-25.09:21:39
SpamBayes Score 5.932213e-06
Marked as misclassified No
Message-id <1282728101.98.0.555622360483.issue9680@psf.upfronthosting.co.za>
In-reply-to
Content
Example


class Meta(type):
    def __new__(cls, name, bases, locals):
        print repr(locals.keys())

class Test(object):
    __metaclass__ = Meta
    A = 1
    B = 2
    C = 3
    D = 4
    E = 5


The above will yield the keys in a somewhat random order, everytime you start up the Python interpreter:

['__module__', 'E', 'C', 'D', 'B', '__metaclass__', 'A']


While the above example is far from complete, it shows the basic dilemma when having some concept that relies on the order in which the elements have been declared and in the order by which they have been processed during the parse phase and ast traversal phase.

In the aforementioned first two phases one can rely on the declaration order, but as soon as we enter the __new__ method, the order becomes irrelevant and is completely lost.

For a framework of mine, I would like the locals dict that is being passed as an argument to the __new__ method to give out references to the keys in the order in which they have been declared in the dict.

Thus, the above example would yield

['__metaclass__', '__module__', 'A', 'B', 'C', 'D', 'E']


The basic reason is that I find it more intuitive to

class A(object):
  __metaclass__ = Meta
  A = 5
  Z = 9

than 

class A(object):
  __metaclass__ = Meta
  __fields__ = ((A,5), (Z,9))


As you might easily guesses, the main application for the above is a new enum type I am currently developing, where the order is important as every new instance of that class must always yield the same ordinals for the individual constants declared.

This should not break with the overall contract of the dict, which defines that keys returned are in no specific order. Thus, adding a specific order to keys in the above locals dict for class instantiation purposes only, would not break with existing code and should be both backwards and forwards compatible.
History
Date User Action Args
2010-08-25 09:21:42carsten.klein@axn-software.desetrecipients: + carsten.klein@axn-software.de
2010-08-25 09:21:41carsten.klein@axn-software.desetmessageid: <1282728101.98.0.555622360483.issue9680@psf.upfronthosting.co.za>
2010-08-25 09:21:40carsten.klein@axn-software.delinkissue9680 messages
2010-08-25 09:21:39carsten.klein@axn-software.decreate