If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.
如果你從Python解釋器中退出棍辕,然后再進入溺森,你之前定義的函數(shù)和變量都會丟失。因此扛门,如果你想要寫一個更長久的程序电媳,你最好使用一個文本編輯器來為解釋器準備輸入并且用這個文件作為程序運行的輸入挚币。這也就是創(chuàng)建一個腳本.當你的程序變得更長萄涯,為了更容易維護,你可能想要把它拆成幾個文件鸯屿。或許你也想在多個程序中使用一個方便的函數(shù)把敢,而不是復制它的定義到每一個程序中。
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
為了支持這點谅辣,Python有一個方法可以把定義放在一個文件中修赞,然后在腳本或解釋器交互地調(diào)用它。這樣的文件稱作模塊桑阶。模塊中的定義可以被 import 導入到其他模塊或主模塊(你在頂級和計算模式下執(zhí)行的腳本中可以訪問的變量集合)柏副。
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__
. For instance, use your favorite text editor to create a file called fibo.py
in the current directory with the following contents:
模塊是包含Python定義和語句的文件。文件名是模塊名加后綴.py
蚣录。在模塊中割择,模塊的名字(是一個字符串)可以通過全局變量__name__
來獲取。例如萎河,使用你最喜歡的文本編輯器在當前目錄創(chuàng)建一個文件fibo.py
包含下面的內(nèi)容:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
現(xiàn)在進入Python解釋器荔泳,然后用下面的命令導入這個模塊:
>>> import fibo
This does not enter the names of the functions defined in fibo
directly in the current symbol table; it only enters the module name fibo
there. Using the module name you can access the functions:
在當前符號表,還沒有直接進入到fibo
中定義的函數(shù)的名稱虐杯。僅僅是進入到模塊名fibo
這里玛歌。使用模塊名你可以訪問函數(shù):
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
If you intend to use a function often you can assign it to a local name:
如果你想要經(jīng)常使用函數(shù),你可以將其賦值給一個局部變量:
>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
6.1. More on Modules 更多關于模塊
A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. [1] (They are also run if the file is executed as a script.)
一個模塊可以包含執(zhí)行語句和函數(shù)定義擎椰。這些語句可以初始化模塊支子。它們只在模塊的名字第一次出現(xiàn)導入語句時執(zhí)行。(當這個文件被當做腳本運行時达舒,它們也會被執(zhí)行值朋。)
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname
.
每一個模塊有它自己私有的符號表,跟模塊中定義的所有函數(shù)使用的全局符號表類似巩搏。所以模塊的擁有者可以在模塊中使用全局變量昨登,不用擔心和用戶的全局變量沖突。另一方面贯底,如果你知道自己的操作篙骡,你可以跟引用它的函數(shù)一樣來引用模塊的全局變量:modname.itemname
.
Modules can import other modules. It is customary but not required to place all import
statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.
模塊中可以導入看其他模塊。把所有的import
導入語句放在模塊的開頭是習慣丈甸,而非必須的糯俗。被導入的模塊的名字被放在導入模塊的全局符號表中。
There is a variant of the import
statement that imports names from a module directly into the importing module’s symbol table. For example:
直接把另一個模塊的名字導入到模塊的符號表中是import
語句的變體睦擂。例如:
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo
is not defined).
這不會引入從本地符號表中進行導入的模塊名稱(在上面的例子中得湘,fibo
是沒有定義的)。
There is even a variant to import all names that a module defines:
甚至還有一個import
導入的變體來導入模塊定義的所有名稱:
>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore (_
). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.
這個可以導入除了以下劃線_
開頭的所有名稱顿仇。在大部分情況下淘正,Python程序員不會使用這個用法摆马,因為它引入了一系列不可知的名稱到解釋器,很可能隱藏了一些你已經(jīng)定義過的鸿吆。
Note that in general the practice of importing *
from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
請注意囤采,普通情況下從一個模塊或包中導入*
是不受歡迎的,因為它經(jīng)常使代碼的可讀性變得很差惩淳。但是蕉毯,在交互式環(huán)節(jié)中為了減少輸入是可以的。
If the module name is followed by as
, then the name following as
is bound directly to the imported module.
如果模塊的名字后面跟著as
思犁,那么as
后面的名字就直接跟導入的模塊綁定在一起代虾。
>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This is effectively importing the module in the same way that import fibo
will do, with the only difference of it being available as fib
.
這實際上是以“import fibo”的方式導入模塊,唯一的區(qū)別在于它可以作為fib
使用激蹲。
It can also be used when utilising from
with similar effects:
當使用from
時同樣也可以使用棉磨,效果一樣:
>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Note :For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload()
, e.g.import importlib; importlib.reload(modulename)
.
注意:為了效率的原因,每一個交互式會話中每個模塊只需要被導入一次学辱。因此乘瓤,如果你要改變你的模塊,你必須重啟解釋器策泣,或者如果僅僅想要改變一個模塊馅扣,可以使用importlib.reload()
.例如:
import importlib
importlib.reload(modulename)
6.1.1. Executing modules as scripts 像腳本一樣執(zhí)行模塊
When you run a Python module with
當你運行一個Python腳本:
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the __name__
set to "__main__"
. That means that by adding this code at the end of your module:
模塊中的代碼將會被執(zhí)行,就跟你導入它一樣着降,把__name__
設置為 __main__
.那也意味把下面的代碼加到你模塊的末尾:
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:
您可以使該文件可用作腳本以及可導入模塊差油,因為命令行解析的代碼僅在模塊作為“主”文件執(zhí)行時才會運行:
$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34
If the module is imported, the code is not run:
如果模塊被導入,代碼不會運行:
>>> import fibo
>>>
This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
這通常要么為模塊提供方便的用戶界面任洞,要么為了測試目的.(以腳本的方式運行模塊可以執(zhí)行測試套件)
6.1.2. The Module Search Path 模塊搜索路徑
When a module named spam
is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py
in a list of directories given by the variable sys.path
. sys.path
is initialized from these locations:
當一個叫做spam
的模塊被導入蓄喇,解釋器首先用搜索是否內(nèi)為置模塊。如果沒有找到交掏,就會在系統(tǒng)變量sys.path
中的列表中查找妆偏。sys.path
初始化為下面的位置:
- The directory containing the input script (or the current directory when no file is specified).
輸入腳本所在的目錄(當沒有文件指定時,取當前目錄) -
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).
PYTHONPATH
(目錄名列表盅弛,語法與shell變量PATH
相同) - The installation-dependent default.
安裝依賴的默認值钱骂。
Note:On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is not added to the module search path.
注意:在支持符號鏈接的文件系統(tǒng)上,包含輸入腳本的目錄是計算符號鏈接后面的挪鹏。換句話說见秽,包含符號鏈接的目錄不會添加到模塊搜索路徑中。
After initialization, Python programs can modify sys.path
. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.
初始化之后讨盒,Python程序員可以修改sys.path
.包含執(zhí)行腳本的目錄放在搜索路徑的開始解取,在標準庫路徑前面。這意味著將加載該目錄中的腳本返顺,而不是庫目錄中的同名模塊禀苦。除非有意更換蔓肯,否則這是一個錯誤。
6.1.3. “Compiled” Python files 編譯Python文件
To speed up loading modules, Python caches the compiled version of each module in the __pycache__
directory under the name module.*version*.pyc
, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as __pycache__/spam.cpython-33.pyc
. This naming convention allows compiled modules from different releases and different versions of Python to coexist.
為了快速加載模塊振乏,Python在module.*version*.pyc
下面的__pycache__
目錄中為每一個模塊緩存了編譯的版本蔗包,按照編譯文件的版本編碼格式;它通常包含Python版本號。例如:在CPython發(fā)行版本3.3中spam.py
的編譯版本將會緩存在__pycache__/spam.cpython-33.pyc
.這樣命名的慣例允許Python中不同的發(fā)行和不同版本的編譯能夠共存慧邮。
Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.
Python 檢查源文件和編譯版本的修改日期來判斷是否過期而需要重新編譯调限。這個是全自動的進程。同樣赋咽,已編譯的模塊是平臺獨立的,所有同樣的庫可以在不同體系架構的操作系統(tǒng)中共享吨娜。
Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.
Python在兩種情況下不會檢查緩存:第一脓匿,從命令行直接導入的模塊總是重新編譯而不會儲存結果。第二宦赠,如果沒有源模塊陪毡,它也不會檢查緩存。為了支持非源(僅編譯)分發(fā)勾扭,已編譯模塊必須在源目錄中毡琉,并且不得有源模塊。
Some tips for experts:
專家提示:
You can use the
-O
or-OO
switches on the Python command to reduce the size of a compiled module. The-O
switch removes assert statements, the-OO
switch removes both assert statements and doc strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have anopt-
tag and are usually smaller. Future releases may change the effects of optimization.
你可以在Python命令中使用-O
或者-OO
開關來減少已編譯模塊的大小妙色。-O
開關移除斷言語句桅滋,-OO
開關移除斷言語句和__doc__
文檔字符串。由于某些程序可能依賴于這些才可用身辨,因此只有知道自己在做什么才能使用此選項丐谋。“優(yōu)化”模塊有一個'opt -`標簽煌珊,通常更小号俐。未來版本可能會改變優(yōu)化的效果。A program doesn’t run any faster when it is read from a
.pyc
file than when it is read from a.py
file; the only thing that’s faster about.pyc
files is the speed with which they are loaded.
一個重新從.pyc
讀取并不會比從.py
文件中讀取運行的快定庵。從.pyc
中讀取唯一快的一點就是他們加載的速度吏饿。The module
compileall
can create .pyc files for all modules in a directory.
compileall
模塊可以為目錄中的所有模塊創(chuàng)建.pyc
文件。There is more detail on this process, including a flow chart of the decisions, in PEP 3147.
有關此過程的更多詳細信息蔬浙,包括決策的流程圖猪落,盡在PEP 3147.
6.2. Standard Modules 標準模塊
Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg
module is only provided on Windows systems. One particular module deserves some attention: sys
, which is built into every Python interpreter. The variablessys.ps1
and sys.ps2
define the strings used as primary and secondary prompts:
Python附帶了一個標準模塊庫,在單獨的文檔:Python庫參考(以下稱為“庫參考”)中進行了描述畴博。一些模塊是在解釋器中內(nèi)置的许布。這些操作提供對不屬于語言核心但仍然內(nèi)置的操作的訪問,以提高效率或提供對系統(tǒng)調(diào)用等操作系統(tǒng)原語的訪問绎晃。這些模塊的集合是一個配置選項蜜唾,它也取決于底層平臺杂曲。例如:winreg
模塊只在windows系統(tǒng)中提供。有一個特殊的模塊值得關注:sys
模塊袁余,內(nèi)置在每一個Python解釋器中擎勘。 變量 sys.ps1
和 sys.ps2
定義了用作主要和次要提示的字符串:
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>
These two variables are only defined if the interpreter is in interactive mode.
這兩個變量只有當解釋器是交互模式下才能定義。
The variable sys.path
is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH
, or from a built-in default if PYTHONPATH
is not set. You can modify it using standard list operations:
變量sys.path
是一個字符串列表颖榜,用于確定解釋器的模塊搜索路徑棚饵。它被初始化為一個取自環(huán)境變量PYTHONPATH
的默認路徑,如果PYTHONPATH
沒有設置掩完,就取內(nèi)置的默認值噪漾。你可以使用標準列表操作來操作它:
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
6.3. The dir()
Function dir()
函數(shù)
The built-in function dir()
is used to find out which names a module defines. It returns a sorted list of strings:
內(nèi)置函數(shù)dir()
用來找出模塊定義的名稱。它返回一個有序的字符串列表:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
'__package__', '__stderr__', '__stdin__', '__stdout__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
'_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook',
'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
'thread_info', 'version', 'version_info', 'warnoptions']
Without arguments, dir()
lists the names you have defined currently:
沒有參數(shù)且蓬, dir()
函數(shù)將會列出你目前已經(jīng)定義的模塊的名字:
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
Note that it lists all types of names: variables, modules, functions, etc.
請注意它列出了所有類型的名稱:變量欣硼,模塊,函數(shù)等等恶阴。
dir()
does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module builtins
:
dir()
函數(shù)不會列出內(nèi)置的函數(shù)和變量诈胜。如果你想要列出這些,他們已經(jīng)在builtins
模塊中定義:
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
'zip']
6.4. Packages 包
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B
designates a submodule named B
in a package named A
. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.
包是一種使用“點模塊名稱”來構造Python模塊命名空間的方法冯事。例如焦匈,“A.B”表示在名為“A”的包中指定名為“B”的子模塊。就像模塊的使用一樣昵仅,使不同模塊的作者不必擔心彼此的全局變量名稱缓熟,使用點模塊名稱可以使NumPy或Pillow等多模塊軟件包的作者從彼此的模塊名稱的擔心中解救出來。
Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav
, .aiff
, .au
), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem):
假設您要設計一組模塊(“包”)摔笤,用于統(tǒng)一處理聲音文件和聲音數(shù)據(jù)荚虚。有許多不同的聲音文件格式(通常由它們的擴展名識別,例如:.wav
籍茧,版述。aiff
,.au
)寞冯,因此您可能需要創(chuàng)建和維護不斷增長的模塊集合在各種文件格式之間進行轉換渴析。您可能還需要對聲音數(shù)據(jù)執(zhí)行許多不同的操作(例如混音,添加回聲吮龄,應用均衡器功能俭茧,創(chuàng)建人工立體聲效果),所以此外您還將編寫一個永無止境的模塊流來執(zhí)行這些行動漓帚。這是您的包的可能結構(以分層文件系統(tǒng)的形式表示):
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
When importing the package, Python searches through the directories on sys.path
looking for the package subdirectory.
當導入包時母债,Python通過sys.path
的路徑來查找包的子路徑.
The __init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string
, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py
can just be an empty file, but it can also execute initialization code for the package or set the __all__
variable, described later.
需要__init __.py
文件才能使Python將目錄視為所包含的包;這樣做是為了防止具有通用名稱的目錄(例如string
)無意中被隱藏在模塊搜索路徑上發(fā)現(xiàn)的有效模塊的后面。在最簡單的情況下,__init __毡们。py
只能是一個空文件迅皇,但它也可以執(zhí)行包的初始化代碼或設置__all__
變量,稍后描述衙熔。
Users of the package can import individual modules from the package, for example:
包的用戶可以從包中導入單個模塊登颓,例如:
import sound.effects.echo
This loads the submodule sound.effects.echo
. It must be referenced with its full name.
這會加載子模塊sound.effects.echo
。必須以其全名引用它红氯。
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
An alternative way of importing the submodule is:
導入子模塊的另一種方法是:
from sound.effects import echo
This also loads the submodule echo
, and makes it available without its package prefix, so it can be used as follows:
這也可以導入子模塊echo
,并且可以不用包前綴來引用框咙,因此可以使用如下:
echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directly:
另一種變化是直接導入所需的函數(shù)或變量:
from sound.effects.echo import echofilter
Again, this loads the submodule echo
, but this makes its function echofilter()
directly available:
再次,這會加載子模塊echo
痢甘,但這會使其函數(shù)echofilter()
直接可用:
echofilter(input, output, delay=0.7, atten=4)
Note that when using from package import item
, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import
statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError
exception is raised.
請注意喇嘱,當使用from package import item
時,該項可以是包的子模塊(或子包)塞栅,也可以是包中定義的其他名稱者铜,如函數(shù),類或變量构蹬。 import
語句首先測試是否在包中定義了該項;如果沒有王暗,它假定它是一個模塊并嘗試加載它悔据。如果找不到庄敛,則引發(fā)[ImportError 導入錯誤
](https://docs.python.org/3/library/exceptions.html#ImportError“ImportError”)異常。
Contrarily, when using syntax like import item.subitem.subsubitem
, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.
當然科汗,當使用類似import item.subitem.subsubitem
的語法時藻烤,除了最后一項其他的都必須是包。最后一項可以是模塊头滔,或者包怖亭。但是不能是前面項定義的類或函數(shù)或變量。
6.4.1. Importing * From a Package 從包中導入*
Now what happens when the user writes from sound.effects import *
? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.
現(xiàn)在當用戶寫from sound.effects import *
時會發(fā)生什么坤检?理想情況下兴猩,人們希望以某種方式傳遞給文件系統(tǒng),找到包中存在哪些子模塊早歇,并將它們?nèi)繉肭阒ァ_@可能需要很長時間,并且導入的子模塊可能會產(chǎn)生不必要的副作用箭跳,這種副作用只有在顯式導入子模塊時才會發(fā)生晨另。
The only solution is for the package author to provide an explicit index of the package. The import
statement uses the following convention: if a package’s __init__.py
code defines a list named __all__
, it is taken to be the list of module names that should be imported when from package import *
is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sound/effects/__init__.py
could contain the following code:
唯一的解決方案是讓包作者提供包的顯式索引。 [import
](https://docs.python.org/3/reference/simple_stmts.html#import)語句使用以下約定:如果包的__init __.py
代碼定義了名為__all__
的列表谱姓,它被視為遇到from package import *
時應導入的模塊名列表借尿。在發(fā)布新版本的軟件包時,由軟件包作者決定是否保持此列表的最新狀態(tài)。如果包作者沒有看到從包中導入*的用法路翻,他們也可能決定不支持它狈癞。例如,文件sound / effects / __ init __.py
可以包含以下代碼:
__all__ = ["echo", "surround", "reverse"]
This would mean that from sound.effects import *
would import the three named submodules of the sound
package.
這意味著from sound.effects import *
將導入sound
包的三個命名子模塊帚桩。
If __all__
is not defined, the statement from sound.effects import *
does notimport all submodules from the package sound.effects
into the current namespace; it only ensures that the package sound.effects
has been imported (possibly running any initialization code in __init__.py
) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py
. It also includes any submodules of the package that were explicitly loaded by previous import
statements. Consider this code:
如果沒有定義__all__
亿驾,聲明from sound.effects import *
不會將包'sound.effects中的所有子模塊導入當前命名空間;它只確保導入了包'sound.effects
(可能在__init __.py
中運行的任何初始化代碼),然后導入包中定義的任何名稱账嚎。這包括由__init __.py
定義的(以及顯式加載的子模塊)任何名稱莫瞬。它還包括由先前的[import
](https://docs.python.org/3/reference/simple_stmts.html#import)語句顯式加載的包的任何子模塊」叮考慮以下代碼:
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
In this example, the echo
and surround
modules are imported in the current namespace because they are defined in the sound.effects
package when the from...import
statement is executed. (This also works when __all__
is defined.)
在這個例子中疼邀,echo
和surround
模塊在當前命名空間中導入,因為在執(zhí)行from ... import
語句時它們是在sound.effects
包中定義的召锈。 (這在__all__
中定義也是有效的旁振。)
Although certain modules are designed to export only names that follow certain patterns when you use import *
, it is still considered bad practice in production code.
雖然某些模塊設計為在使用import *
時只導出遵循某些模式的名稱,但在生產(chǎn)代碼中仍然被認為是不好的做法涨岁。
Remember, there is nothing wrong with using from Package import specific_submodule
! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.
請記住拐袜,使用from packages import specific_submodule
沒有任何問題!實際上梢薪,除非導入模塊需要使用來自不同包的同名子模塊蹬铺,否則這是推薦的表示法。
6.4.2. Intra-package References 包內(nèi)的參考
When packages are structured into subpackages (as with the sound
package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder
needs to use the echo
module in the sound.effects
package, it can use from sound.effects import echo
.
當包被構造成子包時(與示例中的sound
包一樣)秉撇,您可以使用絕對導入來引用兄弟包的子模塊甜攀。例如,如果sound.filters.vocoder
需要該模塊使用sound.effects
包中的echo
模塊時琐馆,它可以使用from sound.effects import echo
规阀。
You can also write relative imports, with the from module import name
form of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround
module for example, you might use:
您還可以使用import語句的“from module import name”形式編寫相對導入。這些導入使用點來指示相對導入中涉及的當前和父包瘦麸。例如谁撼,從surround
模塊,您可以使用:
from . import echo
from .. import formats
from ..filters import equalizer
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__"
, modules intended for use as the main module of a Python application must always use absolute imports.
請注意滋饲,相對導入基于當前模塊的名稱厉碟。由于主模塊的名稱始終為“__ main __”,因此用作Python應用程序主模塊的模塊必須始終使用絕對導入了赌。
6.4.3. Packages in Multiple Directories 多個目錄中的包
Packages support one more special attribute, __path__
. This is initialized to be a list containing the name of the directory holding the package’s __init__.py
before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
包支持另一個特殊屬性墨榄,[__ path__
](https://docs.python.org/3/reference/import.html#path“__ path__”)。這被初始化為一個列表勿她,其中包含在執(zhí)行該文件中的代碼之前保存包的__init __.py`的目錄的名稱袄秩。這個變量可以修改;這樣做會影響將來對包中包含的模塊和子包的搜索。
While this feature is not often needed, it can be used to extend the set of modules found in a package.
雖然通常不需要此功能,但它可用于擴展程序包中的模塊集之剧。
Footnotes 腳注
[1] In fact function definitions are also ‘statements’ that are ‘executed’; the execution of a module-level function definition enters the function name in the module’s global symbol table.
實際上郭卫,函數(shù)定義也是“執(zhí)行”的“語句”;模塊級函數(shù)定義的執(zhí)行會在模塊的全局符號表中輸入函數(shù)名。