Python 中是否有模块的标准别名?

Are there standard aliases for modules in Python?

根据 this post 中提出的指南,我正在更改所有

from module import function
function(agt)

作者:

import module as mdl
mdl.function(agt)

在我的代码中。我正在尝试使用常用别名而不是个人别名。互联网上是否有某种列表总结了所有常用的别名?

例如,这些似乎很常见:

import numpy as np
import math as m
import matplotlib.pyplot as plt

scipy.linalgtimescipy.iocmath 等的别名呢?你用哪个?随意提供其他别名,如果还没有这样的列表,我愿意提出一个(我会更新这个post)。

不,没有完整的模块缩写词列表

没有规范的列表,我不建议在这里制作一个(所以 IMO 并不是真正的地方)。样式指南,包括命名约定,在 PEP8 中为 python 定义,关于导入的部分是 here。好的和有用的建议,但不是导入别名的枚举列表。

关于命名有很多好的规则和建议,其中一些也适用于导入的名称。 This post, for example, I think, can get us at the not-so-surprising etymology of "Math Plotting Library" to "mpl". Following the PEP8 on module names 可以帮助我们完全不需要缩写词。

请注意,您混合了 built-in modules ("time") with standard but third-party libraries ("numpy", which is ubiquitous but Guido declined in 2006 to add to the core 并且必须单独安装)和一般的第三方库(“matplotlib”)6。您 可能 找到内置库和极其常用库的列表(或通过教程找到的间接库),但包含第三方库的可能性似乎要小得多;我建议让包的作者决定他们的标准缩写。 Numpy 是库的一个很好的例子,它的作者在他们自己的教程中使用 "np" 并且有 "standardized" 他们的库使用语法。

FWIW,我不喜欢称数学为 "m"(或者正如一位评论者所建议的那样,"os as o");对于像我这样笨拙的程序员来说,单名变量是灾难的根源......


我还会向您指出 rationale for including the "as" syntax in the first place,它通过消除可能的名称冲突来证明它的合理性(如果您从 scipysympy 导入 cos,你可能会过得很糟糕)。使用它来缩写已经符合 PEP 命名标准的名称(首先,简短易读),即使方便,听起来也不应该得到官方认可。

举个有趣的例子:here, sympy and scipy both tried to use the same abbreviation for a short while, causing the exact problem we hoped to avoid (although scipy now advises not using an acronym at all, )


脚注

  1. Google 也有风格指南; they suggest 使用 import...as "only when [it's] a standard abbreviation (e.g., np for numpy)"。抱歉,他们也推迟了:)
  2. 不是吹毛求疵,但你的问题是 "I am changing all the... [import statements]"(强调我的)。需要明确的是,您 link 说的问题 "The choice between one or the other then, should be based on coding style instead." 有时直接导入函数或 class 是完全明确的,imo。例如,包含 "GaussianProcessRegressor" 导入的 sklearn tutorial 示例不需要进行任何命名空间或缩写。只有您知道您的应用程序,但在大多数情况下,假设该名称足够唯一是安全的
  3. 这个也可以用。我有时会这样使用它,但我不确定这种策略的推荐度如何
  4. 有些人对会话很了解
  5. Reddit doesn't have a list either
  6. 为了澄清评论中的问题,"third party but standard" 和 "third party" 之间的界限非常非正式,并不意味着神圣