Using an OrderedDict for __dict__ in Python 3 using __prepare__

Steven D'Aprano steve+comp.lang.python at
Sun Jan 8 21:21:30 EST 2012

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 for further details.

Here is my code:

from collections import OrderedDict

# The metaclass
class OrderedClass(type):
	# The prepare function
	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):
	def method2(self):


and the results I get:

calling metaclass __prepare__
calling metaclass __new__
  <class '__main__.OrderedClass'>
  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 

And I'm completely flummoxed by the existence of 

What am I doing wrong?


More information about the Python-list mailing list