import ... as' 的命名规范
通常,我们会用 import numpy as np
这行代码来引入 numpy 这个模块。
那么,关于命名有没有一些通用的规则呢?
还有其他模块呢,特别是一些科学计算相关的,比如 scipy
、sympy
和 pylab
,或者像 scipy.sparse
这样的子模块。
1 个回答
10
SciPy在它的文档中推荐使用import scipy as sp
,不过我个人觉得这个建议没什么用,因为这样做只能让你使用到NumPy的一些功能,而不是SciPy自己新增的功能。我自己更常用的是import scipy.sparse as sp
,不过这是因为我经常使用这个模块。
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
当你开始使用更多的库时,可能会遇到更多这样的情况。其实这些简写没有什么固定的规则,你可以随意创造新的简写。除了import lln as library_with_a_long_name
这种情况,其他的简写没有什么通用的约定。
另外,在Python 2.x的程序员中,有一种习惯是会这样做:
# Try to import the C implementation of StringIO; if that doesn't work
# (e.g. in IronPython or Jython), import the pure Python version.
# Make sure the imported module is called StringIO locally.
try:
import cStringIO as StringIO
except ImportError:
import StringIO
不过在Python 3.x中,这种情况就结束了,因为它不再提供StringIO
、pickle
等的部分C实现。