[Python-Dev] super() does not work during class initialization

Martin Teichmann lkb.teichmann at gmail.com
Wed Mar 25 15:29:24 CET 2015


>> I don't think the compiler can determine the order in
>> all cases. Consider:
>>
>>   class Spam:
>>
>>     if moon_is_full:
>>       alpha = 1
>>       beta = 2
>>     else:
>>       beta = 2
>>       alpha = 1
>
> This is also expected to work in class namespaces:
>
>     locals()["alpha"] = 1
>
> The language reference suggests it isn't, there's an open tracker
> issue I filed some time ago to suggest clarifying it but haven't found
> the time to actually sit down and come up with readable wording:
> http://bugs.python.org/issue17960

Well, for sure the compiler cannot deduce things happening at runtime,
but it still has an order in which things appear at compile time. And
for nearly all use cases that's by far enough. We cannot stop people
from doing weird things, but unless there is a use case for those
weird things, we don't need to support them.

And I think that tampering with locals() is not really a good idea. In
your issue you mention that you want that so that you can create
enums programatically. This is already doable by writing:

    from enum import Enum
    from types import new_class

    def cb(ns):
        ns.update({"a{}".format(i): i for i in range(100)})
        return ns

    Calc = new_class("Calc", (Enum,), None, cb)

I think this is simple enough that we don't need another way
of doing it.

Btw, going on-topic again, what should I do to get my patch
to make super() work during class initialization into python?

Greetings

Martin


More information about the Python-Dev mailing list