Metaclasses vs. standard Python reflection?
Carl Banks
imbosol at aerojockey.com
Sat May 3 16:15:37 EDT 2003
tweedgeezer at hotmail.com (Jeremy Fincher) wrote in message news:<698f09f8.0305012053.123ead56 at posting.google.com>...
> I've been looking for examples of metaclasses I can use for a talk I'm
> going to be giving next week, but I've been having trouble finding
> examples that solve problems that wouldn't just as easily be via
> Python's uber-reflective __getattr__/__setattr__ and inheritance.
> Does anyone have a good example of a problem that's solved more
> "beautifully" with metaclasses than with Python's standard reflection
> facilities?
What if you want a class whose bases come out of a tuple? Maybe you
want to determine its bases on the fly. You can't do that with
getattr/setattr. You can do it with the "new" module, but a much more
beautiful way is to use a metaclass:
class BaseIsATuple(type):
def __new__(self,name,bases,clsdict):
assert len(bases) == 1
return type.__new__(self,name,tuple(bases[0]),clsdict)
Then:
dynabases = some_dynamic_calculation_yielding_a_tuple()
class Something(dynabases):
__metaclass__ = BaseIsATuple
--
CARL BANKS
More information about the Python-list
mailing list