Instances behaviour

Peter Otten __peter__ at
Fri Dec 2 12:01:36 CET 2005

Mr.Rech wrote:

> Thanks for your suggestions. They are very usefull and indeed bypass my
> problem. However, I've found a (perhaps) more elegant way to get the
> same result using metaclasses. My idea is to define my classes as
> follows:
>>>> class meta_A(type):
> ....      def __new__(cls, classname, bases, classdict):
>              # define here all special methods
>              newdict = { #special methods dict}
>              classdict.update(newdict) # any suggestion on
> automatically build newdict?
>              return type.__new__(cls, classname, bases, classdict)

Are you intentionally defeating inheritance?
>>>> class B(object):
>           __metaclass__ = meta_A
>           # More methods here
> I know metaclasses are a complete different beast, anyway I find this
> approach more pythonic. Any comment? Suggestion?


Don't use classes when functions suffice.
Don't use inheritance when duck-typing suffices.
Don't use metaclasses when inheritance suffices.
Corollary: don't use metaclasses to solve problems you have just made up.

In short, the simplest solution is most likely the most pythonic, even when
some odd corner cases are not covered. 

Simplicity also has a nice side effect: fewer bugs.


More information about the Python-list mailing list