2015/9/15 Python Basics (12): Modules and Packages

Source: Internet
Author: User
Tags variable scope python script

Modules are the methods used to organize Python code, while packages are used to organize modules.

When the code is very large, we usually divide the code into several organized pieces of code, and then there is a certain connection between each code snippet. The code is shared, so Python allows a module to be transferred, allowing the use of other modules ' properties to take advantage of previous work and to implement code reuse. Those self-contained and organized code snippets are modules, and the actions of attaching attributes from other modules to your module are imported (import)

Modules are logically said, and they are separate files in the physical layer, the file name of the module is the name of the module plus extension. py. Unlike other languages in which you can import classes, you are importing module or module properties in Python.

The namespace of the module
Module names are an important part of their property names, and given a module name, only one module can be imported into the Python interpreter, so there is no name crossover between the different modules. If a atoi () function is created in the module MyModule, its name should be Mymodule.atoi (). So even if there is a name conflict between the attributes, their full authorization name specifies their own namespace through the period property identifier, preventing name collisions from arising.

The import of a module requires a path search process. That is, locate the mymodule.py file in the "predefined areas" of the file (if you are importing MyModule). These predefined areas are just a collection of your Python search paths. Path search and search path concepts are different, the former refers to finding a file, the latter is to find a set of directories.
The default search path is specified when compiling or installing, and it can be modified in one or two places.
One is the PYTHONPATH environment variable that launches the shell command line of Python. The contents of the variable are a set 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 a python script.
After the interpreter is started, the search path can also be accessed, which is stored in the Sys.path variable of the SYS module.
However, it is not a colon-delimited string, but it contains a list of each independent path.
This is just a list, so you can modify it anytime and anywhere, if you need to know what module you want to import, and its path no longer search the path, then just call the Append () method.
Once the modifications are complete, you are ready to load your own modules. As long as a directory in the list contains this file, it will be imported correctly.
When multiple copies of the same module appear in the path, the first module that is found with the search path is used.

Name space
Namespaces are mappings of names (identifiers) to objects. The procedure for adding a name to a namespace involves binding an identifier to the specified object's operation (and adding 1 to the object's reference count).
Python is performed during execution by two or three active namespaces, namely the local namespace, the global namespace, and the built-in namespace.
The Python interpreter first loads the built-in namespace, which is composed of the name of the __builtins__ module. It then loads the global namespace of the execution module, which becomes the active namespace after the module begins execution. If a function is called during execution, a third namespace, local namespace, is created.

About __builtins__ and __builtin__
Now as far as possible only use __builtins__, do not use __builtin__, now all __builtin__ content is in __builtins__, and __builtin__ is not very support.

The relationship between the


namespace and the variable scope
namespace is a purely meaningful mapping between names and objects, and scopes indicate that those names can be accessed from those physical locations of user code. The
name lookup, scoping, and overwrite
name query overwrites the rules that determine the scope to the namespace. When accessing a property, the interpreter must find it in one of three namespaces, starting with the local namespace, and if not, the interpreter will continue to look for the global namespace, and if it fails, it will look in the built-in namespace. If none are found, return a nameerror. The
method of finding this way is to obscure the namespace after it. That is, the local variable overrides the global variable:

def foo (): Print " calling foo () ... "  = print"in foo (), bar is" = "print" In __main__, barwas", Barfoo ()print"in__main__, Baris", Bar

The result is:

inch __main__  iscalling foo () ... inch  is,__main__ is 100

If the following code:

deffoo ():Print "calling foo () ..."    Print "before we assign Bar,bar is", bar Bar= 200Print "in foo (), Bar is", Barbar= 100Print "in __main__, Bar is", Barfoo ()Print "in __main__, Bar is", bar

Then returns:

>>>inch __main__, bar is100calling foo () ... before we assign Bar,bar isTraceback (most recent): File"f:/Desktop/pythonprogram/namespace.py", line 8,inch<module>foo () File"f:/Desktop/pythonprogram/namespace.py", Line 3,inchFooPrint "before we assign Bar,bar is", barunboundlocalerror:local variable'Bar'Referenced before assignment

If you delete one of the rows:

deffoo ():Print "calling foo () ..."    Print "before we assign Bar,bar is", BarPrint "in foo (), Bar is", Barbar= 100Print "in __main__, Bar is", Barfoo ()Print "in __main__, Bar is", bar

The result is:

inch __main__    is-is-__main__ is 100

The above attempt reflects the process of a local namespace covering the global namespace. When I assign a value to bar in a function, bar becomes a local variable, that is, it appears in the local namespace, at which point it will be called before the bar is assigned a value.

Import Module
There are two types of import statements:

Import Module1 Import module2 ... or import module1,module2,...

These two types are not much different, only the readability difference.

Core style: Generally we recommend that all modules be imported at the beginning, preferably in this order
Python Standard library module
Python third-party modules
Application Custom Modules
And then split the three-module import statement with a blank line

From-import statements
This is the specified property of the import module. That is, the specified name is imported into the current scope with the following syntax:

 from import name1[,name2,...]

When the import is too long to be a multiline import, a \ can be wrapped.

Expand import Statement (AS)
When you want to use a module or module property, but want to change a name, you can use your own name to replace the original name of the module, the syntax is as follows:

import Longmodulename as Yourname

The From-import statement can import the name into the current space without having to add a period attribute identifier when it is used, if you want to import all the names into the current namespace:

 from Import *

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

Module built-in functions
__import__ ()
This is the actual function of import, and we use it to do the importing work, and this function is provided to allow users with special needs to overwrite it and implement a 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, locals is the dictionary containing the name of the local symbol table, and fromlist is a list of symbols imported using the From-import statement.

Globals () and locals ()
The two built-in functions return the dictionary of the caller's global and local namespaces, respectively.
Under 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 a module that has already been imported. The syntax is:

Reload (module)

The code in the module is executed at import time, but only once. Subsequent execution of the import statement does not execute the code again, just the module name. and 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 questions can be resolved:
Add hierarchical organizational structure to a flat namespace
Allows programmers to group connected modules together
Allow the Distributor to use the directory structure rather than a whole bunch of confusing files
To help resolve conflicting module names
The package also uses the period property to identify the element that is accessing them.

Suppose there's 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 packages like this:

Import Phone.Mobile.AnalogPhone.Mobile.Analog.dial () or  from Import MobileMobile.Analog.dial () or  from Import analoganalog.dial () or  from Import dialdial ()

There are many __init__.py files in the above directory structure. This is the initialization module, which is used when the From-import statement is imported into the child package. If they are not used, they can be empty files.

Absolute Import
Because of the increasing use of the package, in many cases the import of the child package and the standard library module conflict, the package module will be the same name of the standard library module hidden. For this reason, all imports are now considered absolute, meaning that the names must be accessed through a python path.
Of course, a relative import operation has also been left, the first part is a period, which represents a relative import, and then an additional period is used to indicate at which position level.
As on the directory structure, if we are in digital.py, there are the following import methods:

 from Import # Absolute Import  from Import Dial  from Import  Import g3.dial

2015/9/15 Python Basics (12): Modules and Packages

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.