关于如何导入Python模块,已经问了很多问题,特别是关于是使用绝对导入还是显式相对导入(例如这里)。Python软件基金会建议的import样式可以在这里找到。简而言之,它建议绝对进口。
我写这个问题是因为我认为开发matplotlib的人知道他们在做什么。基于这个假设,并且假设我理解这两种导入之间的主要/明显差异,我将有兴趣了解它们之间的细微差异,这些差异影响了matplotlib的开发人员编写如下内容:import matplotlib
import matplotlib.cbook as cbook
from matplotlib.cbook import mplDeprecation
from matplotlib import docstring, rcParams
from .transforms import (Bbox, IdentityTransform, TransformedBbox,
TransformedPath, Transform)
from .path import Path
这是artist.py
的开头,包含在matplotlib
模块(即matplotlib.artist
)中。我正在看matplotlib-1.5.1。
我想把注意力集中在模块matplotlib.cbook
, matplotlib.transforms
和matplotlib.path
上。这三个都是纯Python模块(即module_name.py
文件)。
为什么选择from matplotlib.cbook import mplDeprecation
而不是from .cbook import mplDeprecation
,为什么选择from .path import Path
而不是from matplotlib.path import Path
?
也许没有特别的原因,这些选择只是反映了不同开发者的不同风格;也许我遗漏了什么。
关于matplotlib代码库,要记住的一件重要的事情是,它非常古老(git的历史可以追溯到2003年,并且又失去了几年),很大(>93k行python, 17k行c++),并且有超过450个贡献者。
在看礼物的责备(2)。X分支,但导入非常稳定)显示:
08:29 $ git blame matplotlib/artist.py | head -n 18
5fca7e31 (Thomas A Caswell 2013-09-25 11:36:00 -0500 1) from __future__ import (absolute_import, division, print_function,
5fca7e31 (Thomas A Caswell 2013-09-25 11:36:00 -0500 2) unicode_literals)
f4adec7b (Michael Droettboom 2013-08-14 10:18:10 -0400 3)
07e22753 (Matthew Brett 2016-06-06 12:08:35 -0700 4) import six
0ea5fff3 (Thomas A Caswell 2015-12-01 14:40:34 -0500 5) from collections import OrderedDict
f4adec7b (Michael Droettboom 2013-08-14 10:18:10 -0400 6)
453e0ece (Nelle Varoquaux 2012-08-27 23:16:43 +0200 7) import re
453e0ece (Nelle Varoquaux 2012-08-27 23:16:43 +0200 8) import warnings
731f6c86 (Michael Droettboom 2013-09-27 09:59:48 -0400 9) import inspect
e1d30c85 (Jens Hedegaard Nielsen 2015-08-18 19:52:48 +0100 10) import numpy as np
b44e8f20 (John Hunter 2008-12-08 23:28:55 +0000 11) import matplotlib
99b89a87 (John Hunter 2008-06-03 20:28:14 +0000 12) import matplotlib.cbook as cbook
c137a718 (Thomas A Caswell 2014-11-23 00:37:28 -0500 13) from matplotlib.cbook import mplDeprecation
527b7d9a (Michael Droettboom 2010-06-11 18:17:52 +0000 14) from matplotlib import docstring, rcParams
b2408c33 (Cimarron Mittelsteadt 2014-09-12 15:58:25 -0700 15) from .transforms import (Bbox, IdentityTransform, TransformedBbox,
b2408c33 (Cimarron Mittelsteadt 2014-09-12 15:58:25 -0700 16) TransformedPath, Transform)
f4adec7b (Michael Droettboom 2013-08-14 10:18:10 -0400 17) from .path import Path
f2a0c7ae (John Hunter 2007-03-20 21:48:31 +0000 18)
你可以看到,这些行在过去的几年里被很多人(显然包括我)最后碰过。
我不会过多地解读这种差异,但如果您想深入了解,请尝试查看这些更改的提交消息。