简体   繁体   中英

Can sys.modules[__name__] throw an error even if __name__ is defined?

Is it possible for __name__ to be defined -- we could write the following in a script somewhere:

x = __name__

... and yet, the line below would throw an error?

module  = sys.modules[__name__]

Unless you tampered with __name__ or sys.modules , no error should be raised as __name__ should always be in sys.modules .

Unless you forgot to import sys .

# No import

sys.modules[__name__] # raise NameError

If you are having a KeyError , you might have overshadowed __name__ .

import sys

__name__ = 'foo'

sys.modules[__name__] # raise KeyError

Or, less likely, you might have overwritten sys.modules .

import sys

sys.module = {}

sys.module[__name__] # raise KeyError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM