[Python-Dev] Providing a mechanism for PEP 3115 compliant dynamic class creation (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Tue Apr 19 16:10:11 CEST 2011
- Previous message: [Python-Dev] Drop OS/2 and VMS support?
- Next message: [Python-Dev] [Python-checkins] cpython (2.7): Fix a few hyphens in argparse.rst.
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
In reviewing a fix for the metaclass calculation in build_class [1], I realised that PEP 3115 poses a potential problem for the common practice of using "type(name, bases, ns)" for dynamic class creation.
Specifically, if one of the base classes has a metaclass with a significant prepare() method, then the current idiom will do the wrong thing (and most likely fail as a result), since "ns" will probably be an ordinary dictionary instead of whatever prepare() would have returned.
Initially I was going to suggest making build_class part of the language definition rather than a CPython implementation detail, but then I realised that various CPython specific elements in its signature made that a bad idea.
Instead, I'm thinking along the lines of an "operator.prepare(metaclass, bases)" function that does the metaclass calculation dance, invoking prepare() and returning the result if it exists, otherwise returning an ordinary dict. Under the hood we would refactor this so that operator.prepare and build_class were using a shared implementation of the functionality at the C level - it may even be advisable to expose that implementation via the C API as PyType_PrepareNamespace().
The correct idiom for dynamic type creation in a PEP 3115 world would then be:
from operator import prepare
cls = type(name, bases, prepare(type, bases))
Thoughts?
Cheers, Nick.
[1] http://bugs.python.org/issue1294232
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message: [Python-Dev] Drop OS/2 and VMS support?
- Next message: [Python-Dev] [Python-checkins] cpython (2.7): Fix a few hyphens in argparse.rst.
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]