简体   繁体   English

为什么需要使用'import'语句显式导入*内置* python模块'sys'?

[英]why does the *built-in* python module 'sys' need to be explicitly imported with an 'import' statement?

The python documentation says: python文档说:

"One particular module deserves some attention: sys, which is built into every Python interpreter." “一个特定的模块值得关注:sys,它内置于每个Python解释器中。”

My understanding is that if a module is built into the Python interpreter itself, then there is no need for an explicit import statement. 我的理解是,如果一个模块内置在Python解释器本身,那么就不需要显式的import语句。 If the sys module is built-in the Python interpreter, then why is an explicit import statement required for the sys module? 如果sys模块内置了Python解释器,那么为什么sys模块需要一个显式的import语句?

sys is imported at Python startup. sys在Python启动时导入。 So when you import sys , it does not actually do anything except bind a variable name to the already-existing module. 因此,当您导入sys ,除了将变量名称绑定到已存在的模块之外,它实际上并不执行任何操作。

When creating a module instance, there is no reason to have the sys name bound in the module scope when many (probably most) modules don't need to use sys . 在创建模块实例时,当许多(可能是大多数)模块不需要使用sys时,没有理由在模块范围中绑定sys名称。 So, that name is not in scope by default. 因此,默认情况下,该名称不在范围内。

import performs two functions: import执行两个功能:

  1. It loads the module from disk, initializing and executing it. 它从磁盘加载模块,初始化并执行它。
  2. It adds the module to the local namespace. 它将模块添加到本地名称空间。

With "built-in" modules item 1 is not an issue, but item 2 is still important; 使用“内置”模块项目1不是问题,但项目2仍然很重要; without it the code would throw a NameError . 没有它,代码会抛出一个NameError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python模块导入 - 为什么组件仅在显式导入时可用? - Python module import - why are components only available when explicitly imported? 禁用嵌入式Python中的内置模块导入 - Disable built-in module import in embedded Python 为什么我需要从 tkinter 模块显式导入字体模块,即使使用“*”导入了完整模块? - Why do I need to explicitly import the font module from the tkinter module even if have imported the full module using “*”? python importlib.import_module 需要显式导入的模块 - python importlib.import_module requires explicitly imported module Python 使用内置模块而不是在 sys.path 中找到的自定义 package - Python using built-in module instead of custom package found in sys.path 为什么检查说我的模块是内置的? - Why does inspect say that my module is built-in? sys模块是否构建在每个python解释器中是什么意思? - What does it mean that the sys module is built into every python interpreter? 导入的模块不导入 - Imported module does not import 为什么我需要包含 sys.path.append 来使用 Python 3.6 导入模块而我的大学不需要? - Why do I need to include sys.path.append to import a module with Python 3.6 and my colleges doesn't need? 从导入的模块覆盖导入模块的内置函数 - Override importing module's built-in functions from imported module
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM