You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

__name__已定义时,sys.modules[__name__]仍可能抛出错误吗?

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

Great question! The short answer is: yes, it can still throw a KeyError—even if __name__ is definitely defined and accessible. Let's break down the scenarios where this happens:

Scenario 1: You've manually modified __name__ to an invalid module name

__name__ is just a string variable, and nothing stops you from changing its value to something that doesn't exist in sys.modules. For example:

import sys

# __name__ is originally set to your module's name (e.g., "my_module")
__name__ = "non_existent_module_123"

# This will raise KeyError because "non_existent_module_123" isn't in sys.modules
module = sys.modules[__name__]

sys.modules maps valid module names (the ones Python uses to track loaded modules) to their module objects. If you overwrite __name__ with a string that's not a key in this dictionary, accessing it will fail.

Scenario 2: The module has been removed from sys.modules

Even if __name__ retains its original value, if someone (or your code) removes the module from sys.modules, accessing sys.modules[__name__] will break. For example:

import sys

# Save the original module name
original_name = __name__

# Remove the module from sys.modules
sys.modules.pop(original_name)

# __name__ is still set to original_name, but the key is gone from sys.modules
module = sys.modules[__name__]  # KeyError here

This is a rare edge case—you usually don't want to remove modules from sys.modules unless you have a very specific reason—but it's a valid scenario where the line would fail.

When is it safe?

In normal execution (running a script as the main module, or importing a module without modifying __name__ or messing with sys.modules), sys.modules[__name__] will always work. __name__ will be set to either the module's import name or "__main__" (for the entry-point script), both of which are guaranteed to exist in sys.modules.

内容的提问来源于stack exchange,提问作者Toothpick Anemone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:46:36