How parametrize classes by class data?
no.email at please.post
Mon Oct 4 17:59:51 CEST 2010
I want to implement a "class of classes", so that, instead of the
spam = MyClass(eggs)
...I can write
spam = MyClass(ham)(eggs)
...where ham is a parameter that will end up as the value of a class
variable of the class returned by MyClass(ham).
In other words, MyClass is a metaclass: a class whose instances
are themselves classes.
In the immediate use I have for such a metaclass, the parameter is
going to be a list of lists of headers, which is used by the __init__
of the generated class to interpret its inputs.
The standard library's collections.namedtuple needs to do something
similar to this, so I thought I could learn how to do it in Python
by studying its source code. I was surprised to discover that
collections.namedtuple achieves this class parametrization by
generating some source code on the fly, from a template, and exec'ing
This looked to me like a rather un-Pythonic hack, but seeing there
in the venerable collections module suggested to me that maybe this
is actually the best way to achieve this effect in Python. Is this
so? If not, please let me know of a better way.
More information about the Python-list