New submission from Carsten Klein <[email protected]>:
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.
----------
components: Interpreter Core
messages: 114890
nosy: [email protected]
priority: normal
severity: normal
status: open
title: Add in declaration order support for the dictionary passed in to the
meta class __init__ and __new__ methods
type: feature request
versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2, Python 3.3
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue9680>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com