Get the current module in Python
It’s sometimes useful to do introspection on the module itself you are writing. But python doesn’t provide any direct way to support this. In fact a PEP about this feature has been rejected.
A little google find a solution to this problem. Here’s the code
import sys # get the current module's name modname = globals()['__name__'] # get the module module = sys.modules[modname] # or more simply as suggested by E.T module = sys.modules[__name__]
import sys
modname = globals()['__name__'] #can this line be omitted?
module = sys.modules[__name__] #we can use __name__ directly, right?
Yes. I just copied that solution without much thinking …
@E.T
我正想说呢,除了主模块外,__name__就行了。
新年快乐!
我的博客地址由 .cn 变为 .org,有空的时候更新一下友情链接吧。