metaclass and customization with parameters

zipher zondervanz at gmail.com
Sat Oct 2 23:10:04 EDT 2004


After searching through comp.lang.python and the web regarding
metaclasses, I could not find an example for customing classes using
metaclass parameters.

I want to be able to create a class at runtime by calling some
function or 'meta-constructor' which returns a customized class and
sets a class attribute according a given parameter.

Ideally, I'd be able to do something like:

>>> Bag = Metadict(filter=int) #Metadict returns a new class named
'Bag'
>>> issubclass(Bag, dict)      #  which is a type of dict
True
>>> Bag.filter                 #  with class attribute set accordingly
<type 'int'>
>>> b = Bag({'pennies': 6.0, 'dimes': 3})  #create instances of this
new class

(Aside:  the issue of magically knowing the variable name (i.e. 'Bag')
in that first assignment statement and setting the class name
accordingly would be ideal, but I could live with passing the name as
a parameter to Metadict if necessary.)

There would also be a number of new and re-defined methods which would
be part of all classes constructed and returned by calls to Metadict. 
For example, somewhere I need to re-define dict's __setitem__ method
to something like:

>>> def __setitem__(self, key, value):
...     self[key] = self.filter(value) #coerce/validate values before
adding to dict

Ideally, all such methods would be in their own class definition since
they will be common to all classes created by Metadict (perhaps they
would need be defined within Metadict itself).


This seems like a simple thing to want, but unusally convoluted to
actually implement.  I'm not even sure where to start.

Any pointers?

Thank you,

zipher



More information about the Python-list mailing list