Imposing metaclass on library
Lulu of the Lotus-Eaters
mertz at gnosis.cx
Wed Dec 18 16:21:39 EST 2002
|Lulu of the Lotus-Eaters <mertz at gnosis.cx> wrote:
|> Here is the situation: I have a library of classes, and I do not want
|> to modify the library. But I would like to cause all -descendents- of
|> library classes to be created with a custom metaclass (within my
|> application that uses the library).
mis6 at pitt.edu (Michele Simionato) wrote previously:
|I wrote the attached program before reading your posting. Maybe a modification
|of that can help you. Warning: it is highly untested !!
I think this variant on Michele's suggestion is a bit more general. I
need to play with it a bit more to make sure it entirely does what I
want, but it looks mostly OK:
"""Import a module using a custom metaclass for class creation
As a byproduct, classic classic are converted to new style classes
"""
import inspect
class import_with_metaclass(object):
"This is a class factory, not a metaclass"
def __init__(cls, module, metaclass):
class Meta(object): __metaclass__ = metaclass
mod = __import__(module)
for key, val in mod.__dict__.items():
if inspect.isclass(val):
setattr(cls, key, type(key, (val, Meta),{}))
#e.g.: random = import_with_metaclass('random', MetaTrace)
--
Keeping medicines from the bloodstreams of the sick; food from the bellies
of the hungry; books from the hands of the uneducated; technology from the
underdeveloped; and putting advocates of freedom in prisons. Intellectual
property is to the 21st century what the slave trade was to the 16th.
More information about the Python-list
mailing list