问题
I was reading some code that looked basically like this:
class Foo(object):
class_name = __module__.replace('_', '-')
To me, that looked really weird (__module__
, what is that?) so I went and looked at the python data-model. A quick search shows that __module__
is a property of class objects and of function objects. However, there is no __module__
available in the global namespace (as can easily be verified by just trying to look at it and observing the NameError
that results ...).
I decided to chalk this up to implementation specific behavior, but as a last check, I decided to test with other implementations I have handy. It turns out that this code executes with1
- Cpython 2.7.6
- Cpython 3.4.0
- jython 2.5.3
- PyPy 2.2.1 (Python 2.7.3)
My question is whether this behavior is actually defined anywhere in the language reference. I'm not sure why I'd want to, but could I safely rely on __module__
being in the class creation namespace or did all the implementors just decide to do this the same way?
1All linux, but I doubt that matters ...
回答1:
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.
来源:https://stackoverflow.com/questions/31148770/is-module-guaranteed-to-be-defined-during-class-creation