【问题标题】:Python click module: is the repetition of 'name' in 'from module import name as name' necessary?Python click 模块:是否需要在“from module import name as name”中重复“name”?
【发布时间】:2023-02-25 10:09:43
【问题描述】:

在新安装的 Pythons 模块 click 源代码中,我遇到了很多带有 import 语句的行,例如:

from .types import BOOL as BOOL
from .types import Choice as Choice
from .types import DateTime as DateTime
from .types import File as File
from .types import FLOAT as FLOAT
from .types import FloatRange as FloatRange
from .types import INT as INT
from .types import IntRange as IntRange
from .types import ParamType as ParamType
from .types import Path as Path
from .types import STRING as STRING
from .types import Tuple as Tuple
from .types import UNPROCESSED as UNPROCESSED
from .types import UUID as UUID

我还没有看到这种语法的用法,所以进行了 Internet 搜索以找出它的作用和原因。

我发现模块名称前的点 . 是必需的,因为它强制导入使用模块自己的本地目录来获取模块,而不是从 Python 中已经存在的同名模块集合中加载模块。

但是我还没有发现在使用as的时候是哪个sense有方法名的重复。到目前为止,我假设此语法用于重命名导入的方法,但事实并非如此。

as method_name 可以从 from .module_name import method_name as method_name 跳过吗?或者这会产生一些我不知道的影响吗?

【问题讨论】:

  • as ... 在这里没有意义。我只能猜测这可能是由某些 IDE 或工具自动创建的(按字母顺序表明)。
  • @MichaelButscher 做 git blame 并查看引用的问题。
  • @KellyBundy 谢谢。所以这是 mypy 的错(如github.com/pallets/click/issues/1879 所述)。

标签: python import


【解决方案1】:

为了将此问题标记为已在此处回答,该答案反映了@MichaelButscher 和@KellyBundy 在该问题的 cmet 中的讨论结果:

via pip 可安装模块中发现名称重复的原因似乎是为了满足通过 mypy 测试以检查上传代码的要求。这是关于github的讨论摘录

这是关于 --no-implicit-reexport 标志的:https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-no-implicit-reexport。点击的在里面.py 有一堆像 from .module import Name 这样的行。启用该标志后,mypy 不会将此类名称视为重新导出,并使其接受您需要执行的代码 from .module import Name as Name。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2021-10-15
    • 2018-11-13
    • 2021-11-03
    • 2022-08-20
    • 2017-03-22
    相关资源
    最近更新 更多