Python BASICS (12): modules and packages, 2015 python

Source: Internet
Author: User

Python BASICS (12): modules and packages, 2015 python

The module is used to organize Python code, while the package is used to organize the module.

When the amount of code is very large, we generally divide the code into several organized code segments, and there is a certain relationship between each code segment. Code sheets are shared. Therefore, Python allows you to call a module and use the attributes of other modules to reuse the previous work results. Code snippets that are self-contained and organized are modules. Attaching attributes of other modules to your modules is more import)

Modules are logical, and they are independent files in the physical layer. The module File Name is the module name plus the extension name. py. Different from other languages that can import classes, Python imports module or module attributes.

Module namespace
Module names are an important part of their attribute names. Given a module name, only one module may be imported to the Python interpreter. Therefore, names cannot be crossed between different modules. If a atoi () function is created in the module mymodule, its name should be mymodule. atoi (). Therefore, even if there is a name conflict between attributes, their full authorization names are specified by the period attribute identifier to prevent name conflicts.

The module import requires a path search process. Find the mymodule. py file in the pre-defined area of the file (if mymodule is imported ). These predefined regions are just a collection of your Python search paths. The concept of path search is different from that of search path. The former is to find a file, and the latter is to find a group of directories.
The default search path is specified during compilation or installation. It can be modified in one or two places.
One is the PYTHONPATH environment variable that starts the shell command line of Python. The content of this variable is a group of directory paths separated by colons. If you want the interpreter to use this variable, make sure that the variable is set or modified before starting the interpreter or executing the Python script.
After the interpreter is started, you can also access the search path, which is saved in the sys. path variable of the sys module.
However, it is not a colon-separated string, but a list containing each independent path.
This is just a list, so you can modify it anytime, anywhere. If you need to know what the module you want to import is, and its path does not search for the path, you only need to call append () method.
After modification, you can load your own modules. As long as a directory in the list contains this file, it will be correctly imported.
When multiple copies of the same module appear in the path, the first module that follows the search path will be used.

Namespace
A namespace is the ing between names (identifiers) and objects. Adding a name to a namespace involves binding an identifier to a specified object (and adding 1 to the reference count of the object ).
During execution, Python consists of two or three activity namespaces: local namespace, global namespace, and built-in namespace.
The Python interpreter first loads the built-in namespace, which consists of the name of the _ builtins _ module. Then load the global namespace of the execution module. After the module starts execution, it becomes the activity namespace. If a function is called during execution, a third namespace, a local namespace, is created.

About _ builtins _ and _ builtin __
Try to use only _ builtins _ instead of _ builtin _. Now all _ builtin _ content is in _ builtins, but _ builtin _ is not supported.


Relationship between namespaces and variable scopes
Namespace is a ing between names and objects in a pure sense, and the scope also indicates that these names can be accessed from the physical locations of user code.
Name Search, scope confirmation, and coverage
The name query overwrites the rules with the specified scope to the namespace. When accessing an attribute, the interpreter must find it in one of the three namespaces, starting with a local namespace. If not, the interpreter will continue to search for the global namespace, if it fails, it will be searched in the internal namespace. If none are found, a NameError is returned.
This sequential search method masks the namespace. That is, local variables overwrite global variables:

def foo():  print "calling foo()..."  bar = 200  print "in foo(), bar is",barbar = 100print "in __main__, bar is", barfoo()print "in __main__, bar is", bar

The result is:

>>> in __main__, bar is 100calling foo()...in foo(), bar is 200in __main__, bar is 100

If the following code is used:

def foo():  print "calling foo()..."  print "before we assign bar,bar is",bar  bar = 200  print "in foo(), bar is",barbar = 100print "in __main__, bar is", barfoo()print "in __main__, bar is", bar

Return:

>>> In _ main __, bar is 100 calling foo ()... before we assign bar, bar isTraceback (most recent call last): File "F:/desktop/PythonProgram/namespace. py ", line 8, in <module> foo () File" F:/desktop/PythonProgram/namespace. py ", line 3, in fooprint" before we assign bar, bar is ", barUnboundLocalError: local variable 'bar' referenced before assignment

If one row is deleted:

def foo():  print "calling foo()..."  print "before we assign bar,bar is",bar  print "in foo(), bar is",barbar = 100print "in __main__, bar is", barfoo()print "in __main__, bar is", bar

The result is:

>>> in __main__, bar is 100calling foo()...before we assign bar,bar is 100in foo(), bar is 100in __main__, bar is 100

The above attempt shows that the local namespace overwrites the global namespace. When I assign a value to a bar in a function, the bar becomes a local variable, that is, it appears in a local namespace. In this case, an error is reported when I call it before assigning a value to the bar.

 

Import Module
There are two import statements:

Import module1import module2. .. or import module1, module2 ,...

There is no big difference between the two types, but only the difference in readability.

Core style: Generally, we recommend that you import all modules at the beginning. It is best to import them in this order.
Python standard library module
Python third-party module
Application custom Module
Then use a blank line to separate the import statements of the three modules.

 

From-import Statement
This is the specified attribute of the import module. That is, to import the specified name to the current scope, the syntax is as follows:

from module import name1[,name2,...]

When the imported content is too long to be imported into multiple rows, use a \ line feed.

Extended import Statement ()
When you want to use a module or module attribute, but want to change the name, you can replace the original name of the module with your own name. The syntax is as follows:

import longmodulename as yourname

 

The from-import Statement can import a name to the current space. You do not need to add a period attribute identifier when using the from-import Statement. If you want to import all the names to the current namespace, you can use:

from module import *

Of course, in practice, this is not a good programming style, it contaminated the current namespace, it is likely to overwrite the existing name of the current namespace.

 

Module built-in functions
_ Import __()
This is the actual function of import. We use this function to complete the import. This function is provided to allow users with special requirements to overwrite it and implement Custom import.
The _ import _ () syntax is:

__import__(module_name[,globals[, locals[, fromlist[]]]])

Module_name is the name of the import module, globals is the dictionary containing the name of the current global symbol table, and locals is the dictionary containing the name of the local symbol table, fromlist is a list of symbols imported using the from-import Statement.

Globals () and locals ()
The two built-in functions return the global and local namespaces of the caller respectively.
In the global namespace, globals () and locals () return the same dictionary, because the local namespace is the global space.

Reload ()
This built-in function can re-import an imported module. Syntax:

reload(module)

The code in the module is executed only once during import. If you execute the import Statement later, the code will not be executed again, but the module name will be bound. Reload () can be executed multiple times.


Package
A package is a hierarchical file directory structure that defines a Python application execution environment consisting of modules and sub-packages.
The following problems can be solved:
Add hierarchical organizational structures to a flat namespace
Allow programmers to combine related modules
Allows distributors to use directory structures instead of a large number of messy files.
Helps resolve conflicting module names
The package also uses the period attribute identifier to access their elements.

Suppose there is such a package
Phone/
_ Init _. py
Common_util.py
Voicedta/
_ Init _. py
Pots. py
Isdn. py
Fax/
_ Init _. py
G3.py
Mobile/
_ Init _. py
Analog. py
Digital. py
Pager/
_ Init _. py
Numeric. py
You can import the package as follows:

Import Phone. mobile. analogPhone. mobile. analog. dial () or from Phone import MobileMobile. analog. dial () or from Phone. mobile import AnalogAnalog. dial () or from Phone. mobile. analog import dialdial ()

 

The preceding directory structure contains many _ init _. py files. This is the initialization module. It is used by the from-import statement when importing sub-packages. If not, they can be empty files.

Absolute Import
As packages are increasingly widely used, importing sub-Packages may conflict with the standard library module in many cases, and the package module will hide the standard library module with the same name. Therefore, all imports are considered absolute, that is, these names must be accessed through the Python path.
Of course, some relative import operations are also left behind. The first part is a period, indicating the relative import, and then an additional period is used to indicate the position level.
If the preceding directory structure is in Digital. py, the following import methods are available:

From Phone. Mobile. Analog import dial # import from. Analog import dialfrom... common_util import setupform... Fax import G3.dial

 

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.