Trying to learn about metaclasses

Steven D'Aprano steve+comp.lang.python at
Sat Jul 30 20:48:25 EDT 2011

bruno.desthuilliers at wrote:

> On 25 juil, 17:36, "Steven W. Orr" <ste... at> wrote:
>> I have been doing a lot of reading. I'm starting to get it. I think it's
>> really cool as well as dangerous,
> Dangerous ??? Why so ? Is there anything "dangerous" in a constructor
> or an initialiser ??? A metaclass is just a class, and a class is just
> an object.

Obviously not dangerous in the sense of "Arghh, I just lost a finger!!!" :)

I think it is fair to talk about language features' power on a continuum,
where something like 1+1 has very little power (it just adds two numbers),
classes have more power, metaclasses more again, and exec even more still.
Power can be used for good things, but it can also be used for bad. I
consider metaclasses to be about equal in power to decorators, but more
obscure and less straightforward. Consider a decorator example:

def func(x):
    return x+1

=> returns "the result is 43"

Surprise! What the function does is barely related to the code you can see.
That's surprising and therefore dangerous. Metaclasses give you the same
ability to surprise the reader, hence, dangerous. That's not necessarily a
bad thing: an oxy-acetylene torch is dangerous, and you shouldn't use one
for lighting a cigarette, but if you need to cut through iron bars in a
hurry, it gets the job done.


More information about the Python-list mailing list