Python Guide - Module

zhaozj2021-02-11  249

?

Chapter directory

6.1 In-depth module

6.1.1 Module Search Path 6.1.2 "Compile" Python File 6.2 Standard Module 6.3 DIR () Function 6.4 Pack

6.4.1 Importing all information from the package (Importing * from a package) 6.4.2 Built-in bag (intra-package) Reference 6.4.3 Package in multiple paths

? 6. Module

If you exit the Python interpreter re-enter, all definitions (variables and functions) previously created are all lost. Therefore, if you want to write some long-term saved programs, it is best to use a text editor to write a program, and the saved file input interpreter. We call it a script. The program becomes longer, you might separate it into several files for your convenience maintenance. You may also want to use a commonly used function in several programs, but don't want to copy its definition to every program.

To support these needs, Python provides a method to get definitions from the file, use in an interactive instance of the script or interpreter. Such files are referred to as an instance; the definition in the module can be imported into another module or main module (the variables that can be called in the most advanced variables when the script is executed, and is in the calculator mode)

The module is a file including Python definitions and declarations. The file name is the module name plus .py suffix. The module name of the module (as a string) can be obtained by the global variable __name__. For example, you can create a file called Fibo.py in the current directory with your own file editor, entry the following:

# Fibonacci NumBers Module

DEF FIB (N): # Write Fibonacci Series Up to N

A, b = 0, 1

While B

Print B,

A, B = B, A B

DEF FIB2 (N): # Return Fibonacci Series Up to N

Result = []

A, b = 0, 1

While B

Result.Append (b)

A, B = B, A B

Return RESULT

Now enter the Python interpreter to import this module with the following command:

>>> IMPORT FIBO

Don't import the functions in the FIBO into the current semantic table directly; it just introduces the module name FIBO. You can access this function as follows by the module name:

>>> 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 want to call a function directly, you can usually give it a local name:

>>> FIB = FIBO.FIB

>>> FIB (500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

? 6.1 in-depth module

The module can include execution statements like a function definition. These statements are usually used for initialization modules. They only execute once when the module is first imported. 6.1

The global semantic table corresponding to all functions in the defined module, each module has its own private language. Therefore, module authors can use some global variables in the module without incorrectly cause errors due to the global variables of the user. On the other hand, if you make sure you need this, you can get the global variables in the module like the function in the module, such as: modname.ItemName. Modules can import (import) other modules. All IMPORT statements are all in the module (or script, etc.), but this is not necessary. The imported module is named in the global semantic table of this module.

One variant of the IMPORT statement is imported from the semantic table named this module directly from the imported module. E.g:

>>> from FIBO IMPORT FIB, FIB2

>>> FIB (500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This will not import module names from the LAN (for example, FIBO is not defined).

There is also a variant to import all naming from the module definition:

>>> from FIBO IMPORT *

>>> FIB (500)

1 1 2 3 5 8 13 21 34 55 89 144 233 377

This can import all named in addition to the underline (_).

6.1.1 Module Search Path

When importing a module called the spam, the interpreter first searches for files named spam.py in the current directory, then searches in the directory list of environment variable pythonpath, and then the path list in the environment variable PATH. If PythonPath is not set, or if the file is not found, then search for the installation directory, in UNIX, usually.: / Usr / local / lib / python.

In fact, the interpreter is specified by the path directory search module specified by the Sys.Path variable, which is initialized, and the input script (or the current directory), the PathPath, and the installation directory are included when the variable is initialized. This allows the Python program (the original, programs; I guess should be "programer", programmer-translator) to learn how to modify or replace the module search directory. It should be noted that these scripts should not be renamed with the standard module in these directorys, so these scripts should not be renamed, otherwise Python will attempt to load these scripts as a module when importing modules. This usually triggers an error. See? 6.2 "Standard Modules" for more information.

6.1.2 "Compile" Python File

For short programs that reference a large number of standard modules, there is an important way to improve startup speed. If there is a file called spam.pyc in the spam.py directory, it is considered a pre-"compilation" of the SPAM module (` `Byte-compiled '', binary compilation) version. This version of the spam.py for creating spam.pyc is recorded in the spam.pyc file, if both do not match, .pyc files are ignored.

Usually you don't need to do anything for creating a spam.pyc file. Once spam.py successfully compiles, try to compile the corresponding version of spam.pyc. If there is any reason, the write is unsuccessful, and the returned spam.pyc file will be considered invalid, and then it is ignored. The content of the spam.pyc file is independent of the platform, so the Python module directory can be shared between the machines of different architectures.

Some advanced techniques:

When calling the Python interpreter with the -o parameter, an optimized code is generated and saved in the .pyo file. The general optimizer does not help; it just deletes an assertion statement. With -o parameters, all code will be optimized; .pyc file is ignored, the .py file is compiled as an optimized code. Passing two -O parameters (-OO) to the Python interpreter perform full optimized binary optimization compilation, which occasionally generates erroneous programs. Currently, the compressed .pyo file is only removed from the binary code, the __doc__ string is removed from the binary code. Because some programs depend on the availability of these variables, you should only use this option only in confirmation. Programs from .pyc files or .pyo files will not be faster than from .py files; .pyc or .pyo file is just faster when they load. When you run the script through the script, you will not create a .pyc or .pyo file for binary code for this script. Of course, move the main code of the script into a module, then import this module with a small deconstruction script, you can increase the start speed of the script. You can also specify a .pyc or dry .pyo file directly in the command line. For the same module (here the routine spam - translator), there can be only spam.pyc files (or spam.pyo, when using the -o parameter) without a spam.py file. This can package the Python code library that is compared to the reverse engineering. CompileAll module? You can create a .pyc file for all modules in the specified directory (or create a .pyo file using the -o parameter). ? 6.2 Standard module

Python has a standard module library and publishes a separate document called the Python Library Reference Manual (hereinafter referred to as "Library Reference Manual"). There are some modules to be placed in the interpreter, and the access interface of these operations is not part of the language kernel, but has been built into the interpreter. This is not only to improve efficiency, but also to provide an interface to an operating system such as system calls. This type of module collection is a configuration option that is dependent on the underlying platform. For example, the AMOEBA module only provides support for the AMOEBA native system. There is a specific module worth noting: SYS ?, This module is built into all Python interpreters. Variables Sys.ps1 and Sys.ps2 define the main prompt and Self-help prompt string:

>>> IMPORT SYS

>>> SYS.PS1

'>>>'

>>> SYS.PS2

'...'

>>> SYS.PS1 = 'C>'

C> Print 'Yuck!'

Yuck!

C>

These two variables are only meaningful in the interaction mode of the interpreter (herein, the original: these TWO VARIABLES ARE ONLY DEFINED IF The Interpreter is in Interactive Mode).

The variable sys.path is a list of strings for the interpreter module search path. It is initialized by environment variables pythonpath. If PythonPath is not within, it is initialized by the built-in default value. You can modify it with standard and string:

>>> IMPORT SYS

>>> sys.path.append ('/ ufs / guido / lib / python')

? 6.3 DIR () function

Built-in function DIR () is used to search for module definition by module name, which returns a list of storage lists:

>>> Import Fibo, SYS >>> DIR (FIBO)

['__name__', 'Fib', 'FIB2']

>>> DIR (SYS)

['__displayhook__', '__doc__', '__exceptHOK__', '__name__', '__stderr__',

'__stdin__', '__stdout__', '_getframe', 'API_Version', 'Argv',

'Builtin_Module_names', 'Byteorder', 'CallStats', 'Copyright',

'DisplayHook', 'Exc_clear', 'EXC_INFO', 'EXC_TYPE', 'EXCEPTHOOK',

'exec_prefix', 'executable', 'exit', 'getDefaultencoding', 'getDlopenflags',

'getRecursionLimit', 'getRefcount', 'HEXVERSION', 'Maxint', 'Maxunicode',

'meta_path', 'Modules', 'Path', 'Path_Hooks', 'Path_Importer_Cache',

'Platform', 'prefix', 'ps1', 'ps2', 'setCheckinterval', 'setdlopenflags',

'setprofile', 'setRecursionLimit', 'settrace', 'stderr', 'stdin', 'stdout',

'Version', 'Version_INFO', 'WarnOptions']

When there is no parameter call, the DIR () function returns the name of your current definition:

>>> a = [1, 2, 3, 4, 5]

>>> Import Fibo, SYS

>>> FIB = FIBO.FIB

>>> DIR ()

['__name__', 'A', 'Fib', 'FIBO', 'SYS']

You should list all types of names: variables, modules, functions, etc.:

DIR () does not list built-in functions and variable names. If you want to list this, they define them in standard modules __buildin__:

>>> IMPORT __BUILTIN__

>>> DIR (__ builtin__)

['ARITHMETICERROR', 'Assertionerror', 'AttributeError',

'DepRecationWarning', 'EOFERROR', 'Ellipsses', 'Environmenterror', 'Exception', 'False', 'FloatingPointError', 'Ioerror', 'Importerror',

'IndentationError', 'IndexError', 'Keyerror', 'KeyboardInterrupt',

'Lookuperror', 'MemoryError', 'NameError', 'None', 'Notimplement',

'NotimplementError', 'Osterror', 'OverflowError', 'OverflowWarning',

'PendingDepRecationWarning', 'ReferenceError',

'RuntimeError', 'RuntimeWarning', 'Standarderror', 'StopItemization',

'Syntaxerror', 'syntaxwarning', 'systemerror', 'systemExit', 'Taberror',

'True', 'TypeError', 'UnboundLocalerror', 'Unicodeerror', 'UserWarning',

'ValueError', 'Warning', 'ZerodivisionError', '__debug__', '__doc__',

'__import__', '__name__', 'ABS', 'Apply', 'Bool', 'Buffer',

'Callable', 'CHR', 'ClassMethod', 'CMP', 'COERCE', 'Compile', 'Complex',

'Copyright', 'Credits', 'DELATTR', 'DICT', 'DIR', 'Divmod',

'Enumerate', 'Eval', 'Execfile', 'Exit', 'File', 'Filter', 'Float',

'getattr', 'globals', 'Hasattr', 'Hash', 'Help', 'HEX', 'ID',

'INPUT', 'INT', 'INTERN', 'Isinstance', 'ISSUBCLASS', 'ITER',

'LEN', 'LICENSE', 'List', 'Locals',' LONG ',' MAP ',' MAX ',' MIN ',' Object ',' Oct ',' Open ',' ORD ',' POW ',' Property ',' Quit ',

'Range', 'Raw_INPUT', 'Reduce', 'Reload', 'Repr', 'Round',

'setttr', 'SLICE', 'StaticMethod', 'Str', 'String', 'Sum', 'Super',

'Tuple', 'Type', 'Unichr', 'Unicode', 'Vars', 'Xrange', 'Zip']

6.4 pack

The package is usually used with a structured module with a "dot module name" namespace. For example, a module named A.B represents a sub-module named "B" in a package called "A". As used as a module to save different module architectures to avoid mutual conflicts between global variables, using dot module names to save different type library architectures like NUNPY or PYTHON IMAGING LIBRARY to avoid naming conflicts between modules.

Suppose you want to design a module set (a "package") to unify the sound files and sound data. There are several different sound formats (usually by their extensions, for example: .wav, .aiff, .au), so in order to convert between different types of file formats, you need to maintain a growing package set. Maybe you also want to do a lot of different operations for sound data (such as mixing, add echo, application balancing function, create an artificial effect), so you have to join an infinite stream module to perform these operations. Your package may be this look (grouped by a graded file system):

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 the module is imported, Python searches the subdirectory of the storage package via the directory list in sys.path.

There must be a __init__.py file existence to make Python as a package as the directory; this is to prevent some directories from using the general name such as "String" without intending to overwrite in the subsequent module search path. The correct module. In the simplest case, __ init__.py can just be an empty file, but it may also contain the initialization code of the package, or set the __all__ variable, and will have a related introduction. The package users can import legitimate modules from the package, for example:

Import snound.effects.echo

This is imported into the Sound.effects.echo submodule. It must be referenced by a complete name.

Sound.effects.echo.echofilter (Input, Output, Delay = 0.7, Atten = 4)

There is a way you select when importing the package:

From Sound.effects Import Echo

This loads the ECHO sub-module and allows it to be used without a packet prefix, so it can call as follows:

Echo.ecHofilter (Input, Output, Delay = 0.7, Atten = 4)

There is also another variant for direct import functions or variables:

From Sound.effects.echo Import Echofilter

This will then load the Echo submodule again, but this can directly call its echofilter () function:

Echofilter (Input, Output, Delay = 0.7, Atten = 4)

It should be noted that when importing the package using the from package import item, this child (item) can be a submodule (or a sub-package) in the package, or other named function, a function, class defined in the package. Or variables. The import statement first checks if there is this child in the package, if not, it assumes this is a module and try loading it. If it does not find it, it will trigger an ImportError exception.

Instead, when using syntax like Import Item.subitem.SubSubItem, these subtries must be packets, and the final child can be package or module, but cannot be class, functions, or variables defined in the previous subkey.

6.4.1 Import all information from the package (Importing * from a package)

So what happens when the user wrote from from Sound.effects IMPORT *? Ideally, always want to find all the submodules in the package in the file system, and then import them. Unfortunately, this operation is not very good on the Mac and Windows platform, and these file systems are not sensitive! There is no way on these platforms to ensure that a file called Echo.py should be imported as a module Echo, Echo or Echo. (For example, Windows 95 has an annoying habit, which will display all filenames as the case of the first letter.) The DOS 8 3 file name restrictions bring another interesting question to the long file name module.

The only solution for the author of the package is to provide a clear package index. The import statement is converted as follows: When you perform from packae import *, if the __init__.py code in the package defines a linked list named __all__, it will be imported according to the module name given in the list. The new version of the package is published when the author can update this list. If the package is imported into all modules in their packages when Import *, it may also decide that it does not support it (import *). For example, Sounds / Effects / __ init__.py This file may include the following code: __ all__ = ["echo", "surround", "reverse"]

This means that the from snound.effects import * statement imports the above three named submodules from the Sound package.

If you don't define __all__, from snound.effects import * statement does not import all submodules from the Sound.effects package. Effects imports to the current namespace, can only be determined to import the Sound.effects package (initialization code that may run __init__.py) and all namings defined in the package will be imported. This imports each name (and explicitly imported sub-module) from __init__.py. It also includes a sub-module that is explicitly imported from the package, considering the following code:

Import snound.effects.echo

Import snound.effects.surround

From Sound.effects Import *

In this example, the Echo and the Surround module import current namespace because they have defined in the Sound.effects package when performing the from ... Import statement (also works like __all__).

It should be noted that habits do not advocate all modules from a package or module to import all modules, as this usually means that readability will be poor. However, doing this in an interactive session can reduce input, and the confirmed module is designed to only export the portion named in the determined mode.

Remember, from package import specific_submodule has no error! In fact, this is a recommended write method unless the imported module needs to use the same name sub-module in other packages.

6.4.2 Built-in package (intra-package)

The sub-module often needs to be referenced to each other. For example, the Surround module may reference the ECHO module. In fact, such reference is so common, so that the import statement will first search the package inside, and then the standard module search path. Therefore, Surround Module can simply call import echo or from echo import echofilter. If you do not find the module to import in the current package, the import statement looks for a top module in accordance with the specified name.

If a sub-package structure is used in the package (like the Sound Pack in the example), there is no convenience method that references the submodule from the adjacent package - the full name of the sub-package must be used. For example, if the Sound.Filters.vocoder package needs to use the Echosa module in the Sound.effects package, it can use from Sound.effects Import Echo.

6.4.3 Package in multiple paths

Package supports another special variable, __path__. This variable initializes a list of directory names before the __init__.py file code is executed. This variable can be modified, which acts on the search function of the subcaps and modules in the package. This feature can be used to expand module sets in the package, but it is not commonly used.

FootNotes

... Somewhere.6.1

In fact, the function definition is both "declaration" and "executable"; the actuator is imported by the function in the global semantic table of the module. (

In Fact Function Definitions Are Are `Executed '; The Execution Enters The Function Name in The Module's Global Symbol Table.)

转载请注明原文地址:https://www.9cbs.com/read-4576.html

New Post(0)