Latest web development tutorials

Python3 module

In the previous sections of the script is python interpreter to program us, if you exit and enter from the Python interpreter, then all the methods and variables you define will have disappeared.

Python provides a way to do this, these definitions stored in a file for some scripts or interactive interpreter instance, this file is called a module.

Module is a definition of all of your files that contains functions and variables whose name suffix .py. Modules can be introduced into other programs to use this module functions and other functions. This is also the use of python standard library.

Here is an example of python standard library modules used.

# 文件名:

import sys

for i in sys.argv:

print('\n\nPython 路径为:', sys.path, '\n')

Implementation of the results are as follows:

$ python 参数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'] 

  • 1, import sys introduced python standard library module; this is the introduction of a module approach.
  • 2, sys.argv is a list of command-line switches are included.
  • 3, sys.path includes a Python interpreter automatically find the path of the list of modules required.

import statement

Want to use Python source file, simply perform another import statement in the source file, the syntax is as follows:

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

When the interpreter encounters the import statement, if the module will be imported in the current search path.

The search path is an interpreter will first search for a list of all directories. As you want to import the module support, you need to order at the top of the script: file code is:

# Filename:

def print_func( par ):
    print ("Hello : ", par)
    return introduced support module:

# Filename:
# 导入模块
import support
# 现在可以调用模块里包含的函数了

Examples of the above output:

$ python3 
Hello :  w3big

A module will only be imported once, no matter how many times you execute import. This prevents the import module is executed over and over again.

When we use the import statement when, Python interpreter is how to find the corresponding file it?

This involves the Python search path, the search path is composed of a series of directory names, Python interpreter will turn from these directories to search for modules introduced.

This looks like an environment variable, in fact, may be determined by defining the search path environment variable manner.

Search path is the Python compiler or installation determined, install new library should also be modified. The search path is stored in the sys module path variable, do a simple experiment in interactive interpreter, enter the following code:

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

sys.path is a list of output, the first of which is an empty string '', represents the current directory (if printed out from a script, you can more clearly see which directory), that we execute python interpreter directory (if the script is the directory where the script is run).

So if like me exist in the current directory with the same name as the file to be introduced into the module, the module will be introduced to block out.

Understand the concept of the search path, you can modify sys.path in a script to introduce some not in the search path of the module.

Now, in the current directory or a directory sys.path interpreter in which to create a file, as follows:

# 斐波那契(fibonacci)数列模块

def fib(n):    # 定义到 n 的斐波那契数列
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b

def fib2(n): # 返回到 n 的斐波那契数列
    result = []
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    return result

Then enter the Python interpreter, use the following command to import this module:

>>> import fibo

This is not defined in fibo directly in the name of the function is written into the current symbol table, but the module name fibo written there.

You can use the module name to access functions:

>>> 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__

If you intend 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

from ... import statement

Python allows you to import a statement from a specific part of the current namespace from the module, the syntax is as follows:

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

For example, to import the module fibo of fib function, 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 statement is not the whole fibo module into the current namespace, it will only fibo Lane fib function introduced in.

From ... import * statement

All the contents of a module are all into the current namespace are possible, simply use the following statement:

from modname import *

This provides an easy way to import a module in all projects. However, this statement should not be too much to use.

Depth module

In addition to the method definition module may also include executable code. These codes are generally used to initialize the module. This code is only the first time is introduced will be executed.

Each module has its own independent symbol table, inside the module to use for all functions as a global symbol table.

Therefore, the author of the module can safely use these global variables in the module without worrying about the other users to engage in a global variable flowers.

From another aspect, when you really know what you're doing, you can also access the function module by modname.itemname such representation.

Modules can import other modules. In a module (or script, or elsewhere) foremost use import to import a module, of course, this is just a convention, rather than mandatory. The name of the imported module will be placed in the symbol table of the current operation of the module.

There is also a method of import, import can be used directly within the module name (function of variables) into your current operating module. such as:

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

This method will not import the module name is introduced in the current character table (so in this case inside, fibo name is not defined).

This is also a way to put a one-time module all (function, variable) names are imported into the current character table module:

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

This will import all the names are in, but those of a single underscore (_) name is not on this case. In most cases, Python programmers do not use this method because names introduced from other sources, is likely to cover the existing definition.

__name__ attribute

When a module is first introduced another program, the main program will run. If we want to be introduced in the module, the module does not execute a program block, we can use __name__ attribute to make this block is executed only in the run-time module itself.

# Filename:

if __name__ == '__main__':

Run the following output:

$ python

Program itself is running

$ python
>>> import using_name

Description: Each module has a __name__ attribute, when its value is '__main__', it indicates that the module itself is running, otherwise it is being introduced.

dir () function

内置的函数 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']

If no argument is given, then the dir () function will list the names of all 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 Module

Python itself with some of the standard library of modules in the Python Library Reference document will be introduced to (that is behind the "Library Reference Document").

Some modules are built directly in the parser, these languages ​​though not some built-in features, but he was able to use a very efficient, even a system-level calls are no problem.

These components can be configured in different forms based on different operating systems, such as the winreg module will only be available to the Windows system.

It should be noted that there is a special module sys, which is built into every Python parser. Variables sys.ps1 and sys.ps2 defines the primary and secondary prompt prompt corresponding string:

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


Package is in the form of a management Python module namespace, using "dotted module names."

For example, a module name is AB, then he said that a package A sub-module B.

If using the module, you do not have to worry about global variables among different modules interaction, like the use of dotted module names in this form, do not worry the case module between different libraries of the same name.

So that different authors can provide NumPy module, or Python graphics library.

Let's assume you want to design a unified voice processing module and a data file (or call it a "package").

Existing variety of different audio file formats (basically distinguished by extension, for example: .wav,: file: .aiff,: file: .au,), so you need to have a set of increasing module for between different formats.

And for the audio data, there are many different operations (such as mixing, adding echo, increase equalizer function to create artificial stereo effect), which you also need a set of how never finish modules to handle these operations.

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

sound/                          顶层包               初始化 sound 包
      formats/                  文件格式转换子包
      effects/                  声音效果子包
      filters/                  filters 子包

In the Import a package when, Python sys.path directories based on the subdirectory to find this package contains.

Only directory contains a file named will be considered as a package, mainly to avoid some of the vulgar abuse of the name (for example, called string) careless affect the search path to a valid module.

In the simplest case, put an empty: file: __ it. Of course, this file may also contain some initialization code or is (will be described later) __all__ variable.

Every time the user can import only a specific module inside the package, such as:

import sound.effects.echo

This will import sub-modules: sound.effects.echo. He must use the full name to access:

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

Another method for introducing the sub-modules are:

from sound.effects import echo

It will also import sub-modules: echo, and he does not need those long prefix, so he could use:

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

Another change is directly introduced into a function or variable:

from sound.effects.echo import echofilter

Again, this method will import sub-modules: echo, and can use his echofilter () function:

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

Note that when using from package import item in this form when the corresponding item can be either inside the package sub-module (sub packages), or other names inside the package definition, such as function, class or variable.

The syntax will first import the item name defined as a package, if not found, then tried to follow a module to import. If not found, congratulations, a: exc: ImportError exception is thrown.

Conversely, if you use this form as import item.subitem.subsubitem import form, except the last one, it must be a package, but the last one can be a module or a package but can not be a class name, function or variable .

Import from a package *

Imagine if we use from sound.effects import * What will happen?

Python will enter the file system, find the package which all sub-modules, one by one, all of them to come into.

But unfortunately, this method works on the Windows platform is not very good, because Windows is a case-insensitive system.

On this platform, no one can vouch called file imported as a module echo or Echo or ECHO.

(For example, Windows 95 is very annoying to capitalize the first letter of each file is displayed) and DOS 8 + 3 naming convention will deal with the issue of long module names do more tangled.

To solve this problem, the only trouble the package author to provide an accurate index of the package.

Import statement following rules: If the package definition file called exists __all__ list of variables, using from package import * time to put all the names in this list as a package import content.

As the author of the package, do not forget after the update package to ensure __all__ also updated ah. You say I will not do it, I will not use the Import * this usage, okay, no problem, why did not you do the boss. Here is an example, in: file: sounds / effects / __ contains the following code:

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

This means that when you use this usage from sound.effects import *, you will import the package inside the three sub-modules.

If __all__ really is not defined, then use this syntax from sound.effects import * time, it does not import any sub-modules in the package sound.effects. He just put all the contents of the package and its sound.effects defined inside to come into (defined may be running initialization code).

This will which defines all of the names to come into. And he will not destroy all explicitly specified module before we introduced this sentence. Look at this part of the code:

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

In this example, before the execution from ... import, package sound.effects the echo and surround modules are imported into the current namespace. (Of course, even if you define __all__ no problem)

Normally we do not advocate the use of * this method to import the module, because often this method will result in reduced readability. But this is really a keystroke can save a lot of effort, and some modules are designed to become the only import through a particular method.

Remember, using from Package import specific_submodule this method will never be wrong. In fact, this is the recommended method. Unless you want to import sub-modules and sub-modules may have other packages of the same name.

If the structure of the package is a sub-package (such as the example for the package is sound), and you want to import the brothers package (same level package) you have to use imported absolute path to import. For example, if you want to use the module sound.filters.vocoder package sound.effects modules echo, you have to write from sound.effects import echo.

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

Whether implicit or explicit relative imports are from the beginning of the current module. Name of the main module is always "__main__", a Python application's main module, you should always use an absolute path references.

Package also provides an additional property __path__. This is a list of directories, each of which has a directory containing the package for this service, you have to be executed before other defined in oh. This variable can be modified for influence inside the module included in the package and the child package.

This feature is not commonly used, typically used to extend the package inside the module.