Is “__module__” guaranteed to be defined during class creation?

前端 未结 1 625
时光取名叫无心
时光取名叫无心 2021-02-05 19:17

I was reading some code that looked basically like this:

class Foo(object):
    class_name = __module__.replace(\'_\', \'-\')

To me, that looke

1条回答
  •  时光取名叫无心
    2021-02-05 19:52

    What the documentation does define is that classes will have a __module__ attribute. It seems the way CPython does this is that it defines a local variable __module__ at the beginning of the class block. This variable then becomes a class attribut like any other variable defined there.

    I can't find any documentation saying that __module__ has to be defined in this way. In particular, I can't find any documentation explicitly saying the attribute has to be define as a local variable in the class body, instead of being assigned as a class attribute at some later stage in class creation. This answer to a different question mentions that it works this way, and shows how it appears in the bytecode. There was a Jython bug that they fixed by making it work the same as CPython.

    I'm guessing this is a CPython implementation detail that was carried over to other implementations. As far as I can tell the documentation doesn't actually say __module__ has to be available inside the class body, only on the class object afterwards.

    0 讨论(0)
提交回复
热议问题