【问题标题】:what is the jargon of the alias variable after import module in Python?Python中导入模块后别名变量的行话是什么?
【发布时间】:2019-09-26 02:34:21
【问题描述】:

Python 生态中有很多包,比如 NumPy、Matplotlib。

为了简化编码,我们通常这样编码

import numpy as np

np 是别名、快捷方式或其他东西。

问题是,这种用法的行话是什么? python doc 的链接会很棒。

【问题讨论】:

  • 请注意,就 Python 而言,导入后名称 numpy 与名称 np 基本相同。 numpynp 都是底层模块对象的本地别名。 Python 只是使用模块的标识符作为默认名称。

标签: python terminology


【解决方案1】:

导入是name binding的一种形式;当前命名空间中的名称绑定到导入的对象。

import statement documentation 称其为标识符,但identifiers are names。导入对象始终绑定到标识符,但 as <identifier> 语法允许您指定要使用的备用名称而不是默认名称。

当将 Python 语法解析为抽象语法树时(这是 CPython 编译器所做的,您可以使用 ast module),然后生成的 ImportImportFrom 节点有 1 个或多个 names , 每个都是ast.alias 类型的对象:

      | Import(alias* names)
      | ImportFrom(identifier? module, alias* names, int? level)

alias 类型有一个name 和一个asname 值,两者都是标识符,而asname 是可选的:

    -- import name with optional 'as' alias.
    alias = (identifier name, identifier? asname)

所以它们只是名称、变量,并且由于它们不同于这些导入的默认值,因此可以将它们称为别名。

【讨论】:

    【解决方案2】:

    asname就不会错。

    【讨论】:

      猜你喜欢
      • 2022-12-09
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2022-01-03
      • 2017-05-31
      相关资源
      最近更新 更多