Python tutorial (6): Module

Source: Internet
Author: User
Document directory
  • 6.1.1 execute the module as a script
  • 6.1.2 module search path
  • 6.1.3 "compile" Python files
  • 6.4.1 import from a package *
  • 6.4.2 reference of built-in packages
  • Packages in multiple directories

If you exit from the python interpreter and enter again, you will find that all the previously defined functions and variables have been lost. Therefore, if you want to write a program that is longer in a certain degree, using a text editor to prepare the interpreter input will improve the situation and use the file instead of the input to execute it. This is a well-known script. As your program grows, you may want to split it into several files for easy maintenance. You may want to use a common function in several programs without copying its definition to every program.

To support this, Python has a way to put definitions in a file and use them in a script or an interactive instance of the interpreter. Such a file is called a module. The definitions in a module can be imported into other modules or the main module (the set of variables accessed in scripts executed in the top-level calculator mode ).

A module is a file containing Python definitions and statements. The file name is the module name with the suffix. py. In a module, the module name (a string) can be obtained using the global variable _ name. For example, use your favorite text editor to create a fibo. py file in the current directory, which contains some content:

Enter the python interpreter and use the following command to import the module:

In this case, the function name directly defined in fibo is not written to the current symbol table, but the module's name is written to it.

You can use the module name to access the function:

If you want to use a function frequently, you can assign it to a local name:

6.1 more modules

The module can contain executable statements and function definitions. These statements are intended to be used to initialize the module. These statements are executed only when the module is imported to other places for the first time.

Each module has its own private symbol table, which is used as a global symbol table by all functions defined in the module. Therefore, a module designer can use global variables in the module without worrying about unexpected conflicts with the user's global variables. In other words, if you know what you are doing, you can touch the global variables in the module and use the same markup method as the previously referenced module function, modname. itemname.

Other modules can be introduced. It is a habit to put all the import statements into the beginning of the module, but it is not necessary to do so. The name of the imported module is placed in the global symbol table of the imported module.

There is a variant of the Import Statement that can directly import the name of a module into the symbol table of another module. For example:

In this way, the module name will not be introduced, and the imported content will be put into the local symbol table (So In the example, the fibo is not defined ).

Even a variant can introduce all the names defined by a module:

This will introduce all names except the names starting with the following dashes. In most cases, Python programmers do not use this function because it introduces an unknown name set to the interpreter, which may hide some of your defined items.

Note: In general, introducing all the names from a module or package is not in favor in practice, because it often causes poor readability of the Code. However, it can be used in interactive sessions to save on input.

Note: for efficiency reasons, each module is introduced only once in a session. If you have changed your module, you must restart the interpreter, or if you want to test the interaction of only one module, you can use imp. reload (), for example: Import IMP; imp. reload (modulename ).

6.1.1 execute the module as a script

When you execute the python module in the following ways:

The code in the module will be executed, just as if you introduced it, But _ name _ will be set to _ main __. This means that the code is added to the end of the module:

You can use the file as a script and an imported module, because the code for parsing the command line runs only when the module is executed as the main file:

If the module is imported, the Code is not executed:

This is usually used to either provide a convenient user interface for the module, or to test (run the module as a script to execute a test unit ).

6.1.2 module search path

When a module named spam is imported, the interpreter first searches for built-in modules with this name. If not, search for a file named spam. py in the Directory List specified by the SYS. PATH variable. SYS. Path is initialized from these locations:

  • Directory containing the input script (or the current directory ).
  • Pythonpath (a list of directory names, which is the same as the syntax of the shell variable path ).
  • Depends on the default value during installation.

After initialization, the python program can modify SYS. Path. The directory containing the running script is placed at the beginning of the search path, before the standard library path. This means that the scripts in that directory will be loaded instead of the modules with the same name in the library directory. This is an error unless the replacement is intended.

6.1.3 "compile" Python files

As an important acceleration for the startup time of short programs that use many standard modules, if spam is found. in The py directory, a file named spam already exists. pyC file, which is assumed to contain a byte-compiled version of the module spam. The modification time of spam. py used to create spam. PyC is recorded in spam. PyC, And the. PyC file is ignored if the two time does not match.

Generally, you do not need to do anything to create the spam. PyC file. No matter when the spam. py file is successfully compiled, an attempt will be made to write the compiled version to spam. PyC. If this attempt fails, it is not an error. If the file is not written for any reason, the spam. PyC file is considered invalid and will be ignored later. The content of the spam. PyC file is platform independent, so a python Module Directory can be shared by machines of different architectures.

Some tips for experts:

  • When the python interpreter is called with the-O flag, the optimized code is generated and stored in the. Pyo file. The optimizer cannot help much now; it only removes the assert statement. When-O is used, all bytecode is optimized; The. PyC file is ignored and the. py file is compiled into the optimized bytecode.
  • Passing two-O flags to the python interpreter (-oo) will enable the bytecode compiler to perform optimization, which may cause program failure in some special cases. Currently, only the document string is removed from the bytecode to generate a more compressed. Pyo file. Because some programs may rely on them to make these available, you should only use this option when you know what you are doing.
  • Reading a program from a. PyC or. Pyo file is not much faster than reading from a. py file. The only fast thing about. PyC or. Pyo files is the speed at which they are loaded.
  • When the Script Name is used in the command line to run the script, the bytecode of the script is never written to the. PyC or. Pyo file. Therefore, moving most of the code of a script into a module generates a small startup script and introduces it to this module can reduce the startup time of a script. You can also name A. PyC or. Pyo file directly in the command line.
  • In the same module, there is a spam. PyC file (or spam. Pyo when-O is used), and no spam. py file is also possible. This can be used to release the Python code library in a difficult form for reverse engineers.
  • The compileall module can create a. PyC file (or. Pyo file when-O is used) for all modules in a directory ).
6.2 standard module

Python has a standard module library, which is described in a separate document. For details about the python library, see. Some modules are built into the interpreter. The access operations they provide are not the core part of the language but are still built in, it is either for efficiency or to provide access to the original content of the operating system, such as the System Call. These module sets are a configuration option, and they also depend on the underlying platform. For example, the winreg module is only available in windows. A special module should be noticed: SYS, which is built into every Python interpreter. The sys. PS1 and SYS. PS2 variables define strings used as the primary and secondary command prompts:

These two variables are defined only when the interpreter is in interactive mode.

The sys. PATH variable is a string list that determines the module search path of the interpreter. It initializes the environment variable pythonpath to a default path, or from a built-in default value if pythonpath is not set. You can use the standard list operation to modify it:

6.3 Dir () function

The built-in function Dir () is used to identify the names defined by each module. It returns a list of sorted strings:

If no parameter exists, Dir () lists the names you have defined:

Note: it lists all types of names: variables, modules, functions, etc.

Dir () does not list the names of built-in functions and variables. If you want to list the names, they are all defined in the standard module Buildins:

6.4 packages

Package is a way to build a python module namespace by using the vertex Module name. For example, a. B indicates that a sub-module named B is in a package named. Just like the use of modules, the authors of different modules do not have to worry about each other's global variable names. The use of module names makes multi-module packages (such as numpy or Python image libraries) the authors no longer have to worry about each other's module names.

Suppose you want to design modules to Process audio files and audio data in a unified manner. There are many audio files in different formats, so you may need to create and maintain a continuously growing set of modules to convert files in different formats. You may also want to perform a variety of different operations on the sound data, so you will write a module stream that never has a header to perform these operations. This is a possible package structure:

When this package is introduced, Python searches for the Steamed Stuffed Bun directory through the directory on SYS. Path.

_ Init __. the py file is required. It allows python to treat these directories as contained packages; in this way, a directory with a common name that occurs later in the module search path accidentally hides a valid module. In the simplest case, __init __. PY may only be an empty file, but it can also execute initialization code for the package or set the _ all _ variable, which will be described later.

Package users can import a single module from the package, for example:

This loads the sub-module sound. effects. Echo. You must use the full name to reference it:

An optional method for importing sub-modules is as follows:

This also loads the submodule echo and makes it available without the package prefix, so it can be used as follows:

Another variant is used to directly import the expected function or variable:

Load the submodule echo and make its function echofilter () available directly:

Note: When Using from package import item, item is either a sub-module (or sub-package) of the package, or some other names defined in the package, such as functions, classes, or variables. The Import Statement first tests whether the item is defined in the package. If not, assume that it is a module and try to load it. If it fails to be found, an importerror exception is triggered.

Otherwise, when using an image like import item. subitem. in subsubitem syntax, all except the last item must be a package. The last item can be a module or a package, but it cannot be a class, function, or variable defined in the previous item.

6.4.1 import from a package *

What happens when a user writes from sound. Effects import? Theoretically, a person wants to get out of the file system in some way, find out which sub-models are stored in the block package, and import them all. This may take a long time, and the sub-module being imported may have undesirable side effects. This side effect should only occur when the sub-module is explicitly imported.

The only solution is that the package author provides an index of the displayed package. The Import Statement uses the following conventions: If a package's _ init __. the py Code defines a list named _ all _, which is considered to be the list of modules to be imported when the from package import * is encountered. It depends on the package author to keep this list up-to-date when a new version of a package is released. The Package authors can also decide not to support it, if they do not see the use of import * from their package. For example, the file sounds/effects/_ init _. py may contain the following code:

This means that from sound. Effects import * will import the three named sub-modules of the sound package.

If _ all _ is not defined, the statement from sound. effects import * is not from sound. import all the sub-modules in the effects package to the current namespace. It only confirms the sound of the package. effects has been imported (possibly run _ init __. any initialization code in Py) and any name defined in the import package. This includes any names defined by _ init _. py (and explicitly loaded submodules ). This also includes any sub-modules of the packages that are explicitly loaded using the previous Import Statement. Consider the following code:

In this example, when the from... Import Statement is executed, the echo and surround modules are imported to the current namespace because they are defined in the sound. Effects package. (This also works when _ all _ is defined .)

When using import *, although it follows a definite pattern, a definite module is designed to output only the name, which is still considered a bad practice in the production code.

Remember, there is no error using from package import specific_submodule. In fact, this is recommended unless the module being imported needs to use sub-modules with the same name from different packages.

6.4.2 reference of built-in packages

When the package is structured into a sub-package (like the sound package in the example), you can use absolute imports to reference the module of the brother package. For example, if the module sound. Filters. Vocoder needs to use the echo module in the package sound. effects, you can use from sound. Effects import echo.

You can also write the relative imports, using the from module Import Name form of the Import Statement. These imports use the leading point (sentence point) to indicate the current and parent packages contained in the relative import. From the surround module, you can use:

Note that the relative imports is based on the name of the current module. Because the name of the main module is always "_ main _", the modules that intend to be used as the main module of the Python application must always use absolute imports.

Packages in multiple directories

The package supports a special attribute __path __. It is initialized to a list of directory names that contain the package's _ init _. py file before the Code in that file is executed. This variable can be changed, which affects searching for modules and sub-packages in the package in the future.

Of course, this feature is not often used. It can be used to expand the module set in a package.

This article is the official website content translation, original address: http://docs.python.org/3/tutorial/modules.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.