为什么将模块导入为_< name>在另一个模块中? [英] Why are modules imported as _<name> in another module?
问题描述
在Python标准库中有几种情况,其中导入的模块名称中带有前导下划线(_
).我想知道为什么这样做是有必要的,因为无论如何它都是以模块的名称命名的,并且from ... import *
将尊重__all__
变量的导入内容.
There are several cases in the Python standard library where modules are imported with a leading underscore (_
) in their name. I wonder why this is necessary, as it is under the module's name anyways and from ... import *
will respect the __all__
variable for what to import.
有人知道为什么要使用/必要吗?
Does anyone know why this is used/necessary?
一个示例是argparse
,它具有以下导入:
An example is argparse
which has the following imports:
import collections as _collections
import copy as _copy
import os as _os
import re as _re
import sys as _sys
import textwrap as _textwrap
推荐答案
在Python中,单个前划线表示这是实现细节,而不是API的一部分".
In Python a single leading underscore means "this is an implementation detail, not part of the API".
这里的要点是要清楚,导入模块(在您的示例中为argparse
)使用导入的,但并未将其作为其自身的一部分公开. API-即,您(作为API的客户端)不应依赖argparse.collections
可用-如果要collections
,则必须显式导入.
The point here is to make clear that the importing module (argparse
in your example) uses the imported one but does not expose them as part of it's own API - ie, you (as a client of the API) should not rely on argparse.collections
being available - if you want collections
, you have to import it explicitely.
这篇关于为什么将模块导入为_< name>在另一个模块中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!