Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

Alex Martelli aleax at mac.com
Fri Jun 23 11:08:45 EDT 2006


Carl Banks <invalidemail at aerojockey.com> wrote:

> sashang at gmail.com wrote:
> > The extra_information is used in MetaThing to tell it what attributes
> > to add to the class. For example:
> >
> > class MetaThing(type):
> >      def __init__(cls, name, bases, dict, extra_information):
> >          super(MetaThing, cls).__init__(name, bases, dict)
> >          #setup the class based on the parameter extra_information
> >          setattr(cls, make_name(extra_information),
> > make_object(extra_information))
> >
> > Does that clarify things?
> 
> Why do the extra attributes need to be part of the class?  ISTM each
> instance has its own class; therefore there it doesn't matter whether a
> member is a class member or an instance member.

It matters for a "member" that is actually a special-method: Python's
automatic search for special methods (except on old-style classes) does
NOT look at per-instance members, only at per-class ones.

But, as many have already said, a custom metaclass is probably not the
optimal tool for this task (and it's definitely wrong to alter a
metaclass's __init__'s signature in incompatible ways -- you would never
be able to make classes with metaclass MetaThing with a normal class
statement, since the intrinsic call to the metaclass's __init__ fails!).


Alex



More information about the Python-list mailing list