I'm using Python 3.1 and trying to create a class using an OrderedDict as 
its __dict__, but it isn't working as I expect.

See http://www.python.org/dev/peps/pep-3115/ for further details.

Here is my code:


from collections import OrderedDict

# The metaclass
class OrderedClass(type):
        # The prepare function
        @classmethod
        def __prepare__(metacls, name, bases): # No keywords in this case
                print('calling metaclass __prepare__')
                return OrderedDict()
        # The metaclass invocation
        def __new__(cls, name, bases, classdict):
                print('calling metaclass __new__')
                for x in cls, name, bases, classdict, type(classdict):
                        print(' ', x)
                return type.__new__(cls, name, bases, classdict)

class MyClass(metaclass=OrderedClass):
        spam = 'Cardinal Biggles'
        ham = 'Ethel the Aardvark'
        def method1(self):
                pass
        def method2(self):
                pass

list(MyClass.__dict__.keys())


and the results I get:

calling metaclass __prepare__
calling metaclass __new__
  <class '__main__.OrderedClass'>
  MyClass
  ()
  OrderedDict([('__module__', '__main__'), ('spam', 'Cardinal Biggles'), 
('ham', 'Ethel the Aardvark'), ('method1', <function method1 at 
0xb71a972c>), ('method2', <function method2 at 0xb71a96ac>)])
  <class 'collections.OrderedDict'>

['__module__', 'method2', 'ham', 'spam', 'method1', '__dict__', 
'__weakref__', '__doc__']


I expected that the output of MyClass.__dict__.keys would match the input 
OrderedDict (ignoring the entries added later, like __module__ and 
__doc__).

And I'm completely flummoxed by the existence of 
MyClass.__dict__['__dict__'].


What am I doing wrong?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to