Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Modules

Python3 Modules

In the previous chapters we were essentially programming with the python interpreter; if you exit the Python interpreter and enter it again, all the methods and variables you defined disappear.

For this, Python provides a way to store these definitions in a file for use by scripts or interactive interpreter instances; such a file is called a module.

A module in Python is a file containing Python definitions and statements; the file name is the module name with a .py suffix.

A module can contain functions, classes, variables and executable code. Modules let us organize code into reusable units, making it easier to manage and maintain.

The role of modules

The following is an example using a module from the python standard library.

Example (Python 3.0+)

#!/usr/bin/python3

File name: using_sys.py

import

sys

print

(

'

The command-line arguments are as follows:

'

)

for

i

in

sys

.

argv

:

print

(

i

)

print

(

'

\n

\n

The Python path is:

'

,

sys

.

path

,

'

\n

'

)

The execution result is as follows:


$ python using_sys.py 参数1 参数2
Command line arguments are as follows:
using_sys.py
参数1
参数2


Python 路径为: ['/root', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] 


import statement

To use a Python source file, simply execute an import statement in another source file; the syntax is as follows:


import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, the module is imported if it is in the current search path.

The search path is a list of all the directories the interpreter searches first. To import the module support, the command must be placed at the top of the script:

Code of the support.py file

#!/usr/bin/python3

Filename: support.py

def

print_func

(

par

)

:

print

(

"

Hello :

"

,

par

)

return

test.py imports the support module:

Code of the test.py file

#!/usr/bin/python3

Filename: test.py

Import the module

import

support

Now the functions contained in the module can be called

support

.

print_func

(

"

Runoob

"

)

The example above produces the following output:


$ python3 test.py 
Hello :  Runoob

Download the code

A module is imported only once, no matter how many times you execute import. This prevents an imported module from being executed over and over again.

When we use an import statement, how does the Python interpreter find the corresponding file?

This involves Python's search path, which consists of a series of directory names; the Python interpreter looks for the imported module in these directories one by one.

Module search path

When importing a module, Python looks for it in the following order:

  1. The current directory.

  2. Environment Variables PYTHONPATH The specified directories.

  3. The Python standard library directory.

  4. .pth The directories specified in the file.

The search path is determined when Python is compiled or installed, and installing new libraries may modify it. The search path is stored in the path variable of the sys module; as a simple experiment, enter the following code in the interactive interpreter:


>>> import sys
>>> sys.path
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
>>> 

The sys.path output is a list whose first item is the empty string '', representing the current directory (if printed from a script, you can see more clearly which directory it is), that is, the directory from which we run the python interpreter (for a script, the directory containing the running script).

Therefore, if like me you have a file in the current directory with the same name as the module to be imported, the module to be imported will be masked.

Once you understand the search path, you can modify sys.path in a script to import modules that are not on the search path.

Now create a fibo.py file in the current directory of the interpreter or in one of the directories in sys.path, with the following code:

Example

Fibonacci sequence module

def

fib

(

n

)

:

Define the Fibonacci sequence up to n

a

,

b

=

0

,

1

while

b

<

n

:

print

(

b

,

end

=

'

'

)

a

,

b

=

b

,

a

b

print

(

)

def

fib2

(

n

)

:

Return the Fibonacci sequence up to n

result

=

[

]

a

,

b

=

0

,

1

while

b

<

n

:

result

.

append

(

b

)

a

,

b

=

b

,

a

b

return

result

Then enter the Python interpreter and import this module with the following command:


>>> import fibo

This does not write the names of the functions defined directly in fibo into the current symbol table; it only writes the name of the module fibo there.

The functions can be accessed using the module name:

Example

fibo

.

fib

(

1000

)

1

1

2

3

5

8

13

21

34

55

89

144

233

377

610

987

fibo

.

fib2

(

100

)

[

1

,

1

,

2

,

3

,

5

,

8

,

13

,

21

,

34

,

55

,

89

]

fibo

.

name

'

fibo

'

If you plan to use a function often, you can assign it to a local name:


>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

The from ... import statement

Python's from statement lets you import a specified part of a module into the current namespace; the syntax is as follows:


from modname import name1[, name2[, ... nameN]]

For example, to import the fib function of the module fibo, use the following statement:


>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This declaration does not import the whole fibo module into the current namespace; it only brings in the fib function from fibo.

Giving a module an alias

Use the as keyword to give an alias to a module or function:


import numpy as np  # 将 numpy 模块别名设置为 np
from math import sqrt as square_root  # 将 sqrt 函数别名设置为 square_root

The from ... import * statement

It is also possible to import all the contents of a module into the current namespace, simply by using the following declaration:


from modname import *

This provides a simple way to import all the items in a module.

Not recommended, as it easily causes naming conflicts.


More on modules

Besides method definitions, a module can also contain executable code. This code is generally used to initialize the module, and is executed only when the module is imported for the first time.

Each module has its own separate symbol table, used as the global symbol table for all the functions inside the module.

Therefore, the author of a module can safely use these global variables inside the module without worrying about mixing them up with the global variables of other users.

On the other hand, if you really know what you are doing, you can also access functions inside a module with a notation such as modname.itemname.

A module can import other modules. Using import at the very beginning of a module (or script, or elsewhere) to import a module is only a convention, not a requirement. The name of the imported module is placed in the symbol table of the module currently being operated on.

There is another way to import, using import to bring the names inside a module (functions, variables) directly into the current module. For example:


>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This form of import does not put the name of the imported module in the current symbol table (so in this example the name fibo is not defined).

There is also a way to import all the names (functions, variables) in a module into the current module's symbol table at once:


>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names, except those starting with a single underscore (_). In most cases Python programmers do not use this method, because names introduced from other sources are likely to override existing definitions.


name property

When a module is imported for the first time by another program, its main program runs.

If we want a certain block of a module not to run when the module is imported, we can use the name attribute to make that block run only when the module itself is run.


#!/usr/bin/python3
# Filename: using_name.py

if __name__ == '__main__':
   print('程序自身在运行')
else:
   print('我来自另一模块')

The output is as follows:


$ python using_name.py
程序自身在运行

$ python
>>> import using_name
我来自另一模块
>>>

** Note: every module has a name attribute.**

Explanation:name The difference between main Those are double underscores; _ _ is written this way with the space in the middle removed.


The dir() function

The built-in dir() function can find all the names defined in a module. It returns them as a list of strings:


>>> 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']

If no argument is given, the dir() function lists all names currently defined:


>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir() # 得到一个当前模块中定义的属性列表
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
>>> a = 5 # 建立一个新的变量 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # 删除变量名a
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
>>>

Standard modules

Python itself comes with a library of standard modules, which are described in the Python Library Reference (the "Library Reference" later on).

Module name Description
math Mathematical operations (such as square roots and trigonometric functions)
os Operating system related functions (such as file and directory operations)
sys System-related parameters and functions
random Generate a random number
datetime Handling dates and times
json Handle JSON data
re Regular expression operations
collections Provide additional data structures (such as defaultdict and deque)
itertools Provide iterator tools
functools Higher-order function tools (such as reduce and lru_cache)

Some modules are built directly into the interpreter; although they are not built-in features of the language, they can be used very efficiently, even for system-level calls.

These components are configured differently depending on the operating system; for example, the winreg module is only provided on Windows systems.

Note that there is a special module sys, built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings for the primary and secondary prompts:


>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Runoob!')
Runoob!
C> 

package

Packages are a way of managing the namespace of Python modules, using "dotted module names".

For example, if a module is named A.B, it means the submodule B in a package A.

Just as you do not need to worry about global variables in different modules affecting each other, using dotted module names means you do not need to worry about modules in different libraries having the same name.

In this way different authors can all provide a NumPy module, or Python graphics libraries.

Suppose you want to design a set of modules for uniformly handling sound files and data (called a "package").

There are many different audio file formats (mostly distinguished by their extensions, for example .wav, :file:.aiff, :file:.au), so you need an ever-growing set of modules to convert between formats.

And for this audio data there are many different operations (such as mixing, adding echoes, adding equalizer functions and creating artificial stereo effects), so you also need an endless set of modules to handle those operations.

Here is one possible package structure (in a hierarchical file system):


sound/                          顶层包
      __init__.py               初始化 sound 包
      formats/                  文件格式转换子包
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  声音效果子包
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  filters 子包
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

When importing a package, Python looks for the subdirectories contained in the package using the directories in sys.path.

A directory is only recognized as a package if it contains a file called init.py; this is mainly to prevent common names (such as string) from accidentally affecting valid modules on the search path.

In the simplest case, just put an empty :file:init.py there. Of course this file can also contain initialization code or assign a value to the __all__ variable (described later).

Users can import only a specific module from a package at a time, for example:


import sound.effects.echo

This imports the submodule sound.effects.echo. It must be accessed using its full name:


sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

Another way to import a submodule is:


from sound.effects import echo

This also imports the submodule echo, and it does not need the long prefix, so it can be used like this:


echo.echofilter(input, output, delay=0.7, atten=4)

A variation is to import a function or variable directly:


from sound.effects.echo import echofilter

Again, this imports the submodule echo, and its echofilter() function can be used directly:


echofilter(input, output, delay=0.7, atten=4)

Note that with the form from package import item, the corresponding item can be either a submodule (subpackage) of the package or another name defined in the package, such as a function, class or variable.

The import syntax first treats item as a name defined by the package; if it is not found, it then tries to import it as a module. If it is still not found, an :exc:ImportError exception.

Conversely, if you use a form such as import item.subitem.subsubitem for importing, all but the last item must be packages, while the last item can be a module or a package, but not the name of a class, function or variable.


Importing * from a package

What happens if we use from sound.effects import *?

Python goes into the file system, finds all the submodules in the package and imports them one by one.

But this method does not work very well on the Windows platform, because Windows is a case-insensitive system.

On Windows, we cannot tell whether a file called ECHO.py is imported as the module echo, Echo or ECHO.

To solve this problem, we only need to provide an exact package index.

The import statement follows this rule: if the package definition file ** init.py** contains a list variable called all , then when from package import * is used, all the names in that list are imported as the package contents.

As the author of a package, do not forget to keep all updated after updating the package.

The following example in file:sounds/effects/init.py contains the following code:


__all__ = ["echo", "surround", "reverse"]

This means that when you use from sound.effects import *, only these three submodules of the package are imported.

If both the all If it is really not defined, then using the syntax **from sound.effects import *** will not import any submodules of the package sound.effects. It only imports the package sound.effects and everything defined in it (possibly running the initialization code defined in __init__.py).

This will import all the names defined in init.py, and it will not break any explicitly imported modules from before this statement. Look at this code:


import sound.effects.echo
import sound.effects.surround
from sound.effects import *

In this example, before from...import is executed, the echo and surround modules of the package sound.effects are both imported into the current namespace. (Of course, if all is defined, there is no problem at all)

Usually we do not recommend using * to import modules, because it often makes code less readable. However, it does save a lot of typing, and some modules are designed to be imported only in a specific way.

Remember, using from Package import specific_submodule this method is never wrong. In fact it is the recommended approach, unless the submodule you are importing may have the same name as a submodule of another package.

If the package in the structure is a subpackage (as in this example for the package sound) and you want to import a sibling package (a package at the same level), you must use an absolute import path. For example, if the module sound.filters.vocoder wants to use the module echo in the package sound.effects, you must write from sound.effects import echo.


from . import echo
from .. import formats
from ..filters import equalizer

Both implicit and explicit relative imports start from the current module. The name of the main module is always "main", and the main module of a Python application should always use absolute path references.

Packages also provide an extra attribute __path__. This is a list of directories, each of which contains an __init__.py serving this package; you must define it before the other __init__.py files are executed. This variable can be modified to affect the modules and subpackages contained in the package.

This feature is not commonly used; it is generally used to extend the modules inside a package.