[Python] modules and packages

Source: Internet
Author: User

I. Module

Usually the module is a file, the import directly using imports just fine. The file types that can be used as module are ". Py", ". Pyo", ". PYc", ". PYD", ". So", and ". dll".

Two. Package

Typically, a package is always a directory, you can import a package using imports, or from + Import to import some of the modules in the package. A document headed by the package directory is __init__.py. Then there are some module files and subdirectories, if there are __init__.py in the subdirectory then it is the child package of this package.

I. Module you can import a source code file as a module using the import statement. For example:

[Python]View Plain copy
  1. # file:spam.py
  2. A = PNS # a variable
  3. def foo: # a function
  4. print "I ' m foo"
  5. Class bar: # a category
  6. def grok (self):
  7. print "I ' m Bar.grok"
  8. b = Bar () # Create an instance

This file can be imported as a module using the Import spam statement. When importing the module, the system should do the following three things:

1. Create a namespace for the objects defined in the source code file, which allows access to the functions and variables defined in the module.
2. Execute the source code file in the newly created namespaces.
3. Create an object called the source code file that references the namespace of the module, which allows access to functions and variables in the module, such as:

[Python]View Plain copy
    1. Import spam # Importing and running the module spam
    2. Print SPAM.A # Accessing the properties of the module spam
    3. Spam.foo ()
    4. c = Spam.bar ()

You can import multiple modules at the same time by separating the module names with commas:

[Python]View Plain copy
    1. Import socket, OS, regex

Module import can use the AS keyword to change the module's Reference object name:

[Python]View Plain copy
    1. Import OS as System
    2. Import socket as NET, thread as threads
    3. System.chdir ("..")
    4. Net.gethostname ()

Use the FROM statement to import an object from a module directly into the current namespace. The FROM statement does not create a reference object to the module namespace, but instead puts one or more objects of the imported module directly into the current namespace:

[Python]View Plain copy
    1. From socket import gethostname # GetHostName is placed as current namespace
    2. Print gethostname () # Direct Call
    3. Socket.gethostname () # throws an exception Nameerror:socket

The FROM statement supports comma-delimited objects, or you can use an asterisk (*) to represent all objects in the module that begin with an underscore:

[Python]View Plain copy
    1. From socket Import gethostname, Socket
    2. From Socket Import * # Loading all objects into the current namespace

However, if a module has a list __all__ defined, the From module import * statement can only import objects that exist in the __all__ list.

[Python]View Plain copy
    1. # module:foo.py
    2. __all__ = [ ' bar ', ' spam '] # defines objects that can be imported using ' * '

In addition, as can also be used in conjunction with from:

[Python]View Plain copy
    1. From socket import gethostname as hostname
    2. h = hostname ()

The import statement can be used anywhere in the program, and you can import the same module multiple times in the program, but the code in the module * is only executed when the module is first imported. The following import statement simply creates a reference to the module namespace. The Sys.modules dictionary holds the mapping of module names to module objects for all imported modules. This dictionary is used to determine whether an import statement is required to import the most recent copy of a module.

The From Module import * Statement can only be used at the top level of a module. * Special Note *: Because of a scope conflict, the FROM statement is not allowed in the function.
Each module has a __name__ property, which is a string that contains the name of the module. The top-most module name is __main__. command line or interactive mode the program runs inside the __main__ module. With the __name__ attribute, we can have different behaviors for the same program on different occasions (executed individually or imported), as in the following:

[Python]View Plain copy
    1. # Whether the check is performed separately or imported
    2. if __name__ = = ' __main__ ':
    3. # Yes
    4. Statements
    5. Else
    6. # No (may be imported as a module)
    7. Statements


Module Search Path
When the module is imported, the interpreter searches the Sys.path list, which holds a list of directories. The value of a typical Sys.path list:
Linux:
[' ', '/usr/local/lib/python2.0 ',
'/usr/local/lib/python2.0/plat-sunos5 ',
'/usr/local/lib/python2.0/lib-tk ',
'/usr/local/lib/python2.0/lib-dynload ',
'/usr/local/lib/python2.0/site-packages ']
Windows:
[', ' c:\\windows\\system32\\python24.zip ', ' C:\\Documents and Settings\\weizhong ', ' c:\\python24\\dlls ', ' C:\\ Python24\\lib ', ' C:\\python24\\lib\\plat-win ', ' c:\\python24\\lib\\lib-tk ', ' c:\\python24\\lib\\site-packages\\ Pythonwin ', ' c:\\python24 ', ' c:\\python24\\lib\\site-packages ', ' c:\\python24\\lib\\site-packages\\win32 ', ' C:\\ Python24\\lib\\site-packages\\win32\\lib ', ' C:\\python24\\lib\\site-packages\\wx-2.6-msw-unicode ']
An empty string represents the current directory. To add a new search path, simply add the path to this list.

module Import and assembly
So far, the modules described in this chapter are text files that contain Python source code. However, the module is not limited to this, there are four types of modules that can be imported into the import statement:
? programs written using Python (. py file)
? C or C + + extensions (compiled as shared libraries or DLL files)
? package (contains multiple modules)
? Built-in modules (written in C and linked to the Python interpreter)
When querying module Foo, the interpreter looks for the following files (directories are also one of the files) in the order of the directories in the Sys.path list:
1. directory Foo defined as a package
2.foo.so, foomodule.so, FOOMODULE.SL, or Foomodule.dll (compiled extensions)
3.foo.pyo (when using the-O or-oo option only)
4.foo.pyc
5.foo.py

For a. py file, when a module is first imported, it is assembled into a byte code, and the bytecode is written to a. pyc file with the same name. Subsequent import operations read the. pyc file directly instead of the. py file. (This situation regenerates the. pyc file unless the modification date of the. py file is updated.) When the interpreter uses the-o option, the file with the same name with the. pyo extension is used. The contents of the Pyo file, while removing the line number, the assertion, and other debugging information bytecode, are smaller and run faster. If you use the-oo option instead of-O, the document string is also ignored when you create the. pyo file.
If all paths provided by Sys.path are found to fail, the interpreter continues to look in the built-in module and throws a Importerror exception if it fails again.
The Assembly of the. PYc and. pyo files, when and only when the import statement executes.
When the import statement searches for files, the file name is case-sensitive. This is true even on systems with file system case insensitivity (windows, etc.). This way, import foo imports only the file foo.py and not the foo.py.

re-importing modules
If you update a module that has already been imported with an import statement, the built-in function reload () can re-import and run the updated module code. It requires a module object as a parameter. For example:
Import Foo
... some code ...
Reload (foo) # re-import foo
The new import code is used for the module after reload () is run, but reload () does not update objects created with the old module, so there is a possibility that the old and new versions of the object will coexist. * Note * Modules compiled with C or C + + cannot be re-imported through the reload () function. Remember a principle and do not use the reload () function unless you are in the process of debugging and development.

2. Package
Several modules that are closely related should be organized into a single package for easy maintenance and use. This technique can effectively avoid namespace collisions. Create a folder with the name of the package name and create a __init__.py file under that folder to define a package. You can store resource files, compiled extensions, and child packages under this folder as needed. For example, a package might have the following structure:
graphics/
__init__.py
primitive/
__init__.py
lines.py
fill.py
text.py
...
graph2d/
__init__.py
plot2d.py
...
graph3d/
__init__.py
plot3d.py
...
formats/
__init__.py
gif.py
png.py
tiff.py
jpeg.py

The import statement imports the modules in the package in several ways:

[Python]View Plain copy
    1. import graphics.primitive.fill < span class= "comment" > #导入模块Graphics. Primitive.fill, module properties can only be accessed by full name, such as  graphics.primitive.fill.floodfill (img,x,y , color).   
    2. from graphics.primitive import fill#  import module fill  The module properties can only be accessed in  fill. Property names, such as   Fill.floodfill (Img,x,y,color).   
    3. from  graphics.primitive.fill import floodfill # Import the module fill , and put the function FloodFill into the current namespace, directly accessing the imported properties, such as  floodfill (Img,x,y,color).   

The code in the file __init__.py runs regardless of which part of the package is imported. The contents of this file are allowed to be empty, but typically it is used to store the initialization code of the package. All __init__.py files that are encountered by the import process are run. Therefore, the import Graphics.Primitive.fill statement runs the __init__.py file under the Graphics and Primitive folders sequentially.

The following statement is ambiguous:

[Python]View Plain copy
    1. From graphics.primitive Import *

The original intent of this statement is to import all modules under the Graphics.primitive package into the current namespace. However, because of the different file name rules between different platforms (such as case sensitive issues), Python does not correctly determine which modules are to be imported. This statement only runs sequentially The __init__.py file under the Graphics and Primitive folders. To solve this problem, you should define a list of name all in the __init__.py below the primitive folder, for example:

[Python]View Plain copy
    1. # graphics/primitive/__init__.py
    2. __all__ = ["lines","text","fill",...]

This allows the upper statement to import all the modules in the list.

The following statement executes only the __init__.py file under the graphics directory, without importing any modules:

[Python]View Plain copy
    1. Import Graphics
    2. Graphics.Primitive.fill.floodfill (Img,x,y,color) # failed!

However, since the import graphics statement will run __init__ under the graphics directory: PY file, we can take the following measures to solve this problem:

[Python]View Plain copy
    1. # graphics/__init__.py
    2. Import Primitive, graph2d, graph3d
    3. # graphics/primitive/__init__.py
    4. Import lines, fill, text, ...

The import graphics statement then imports all of the submodules (only the full name can be used to access the properties of the modules).

Sys.path and Sys.modules
Sys.path contains the lookup path of module;
The sys.modules contains the dict of all the modules currently being load (which contains the modules of builtin);

[Python] modules and packages

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.