[Python-3000] Metaclasses in Py3K

Talin talin at acm.org
Fri Dec 8 10:54:34 CET 2006

I'd like to see metaclasses have additional capabilities in Py3K, and 
one thing I'd like is for metaclasses to be able to have access to the 
order of declarations within a class.

If I understand correctly, in the current Python a class definition is 
essentially a suite with ordinary local variables; once that suite 
finishes executing, the locals() dict becomes the class's __dict__. The 
metaclass slips in between these two phases of construction, in that it 
can examine or modify the dict before it becomes a class.

Suppose, however, that the metaclass could hook into the get/set 
operations of the locals() dict itself. In other words, the 
__metaclass__ statement would have a side-effect of replacing the 
locals() dict with a mapping object supplied by the metaclass.

This would allow the metaclass to intercept individual variable 
assignments as they occur, rather than taking the whole dict in at once.

I can think of a ton of applications for this. For example, you could 
implement the functionality of __slots__ as a metaclass, allowing you to 
define the slots using regular Python syntax rather than having to pass 
in a list of name strings. You could define C structures using regular 
Python syntax. You could declare CORBA or other IDL interfaces using 
Python syntax and appropriate decorators. You might even be able to do 
things like enumerations using metaclasses.

-- Talin

More information about the Python-3000 mailing list