Metaclasses - magic functions

Ian Kelly ian.g.kelly at
Tue Dec 20 18:26:04 EST 2016

On Tue, Dec 20, 2016 at 2:04 PM, Mr. Wrobel <mr at> wrote:
> Hi,
> Quick question, can anybody tell me when to use __init__ instead of __new__
> in meta programming?
> I see that __new__ can be used mostly when I want to manipulate with class
> variables that are stored into dictionary.
> But when to use __init__? Any example?

__new__ is useful because of its power. You can use it to do things
like alter the name of the class or its base classes, or modify class
attributes before the class is created. The latter is interesting
mostly because it allows you to set the __slots__ or do something
interesting with the __prepare__ hook (although the only interesting
thing I've ever seen done with __prepare__ is to use an OrderedDict to
preserve the the definition order of the class attributes; now that
Python 3.6 does this by default it's probably obsolete).

__init__ is simpler than __new__. If you don't need to do any of the
fancy stuff above, you should probably use __init__ instead.

I can't think of any reason why one would ever want to use both on a metaclass.

More information about the Python-list mailing list