Python Import and pythonimport

Source: Internet
Author: User

Python Import and pythonimport

Http://blog.csdn.net/appleheshuang/article/details/7602499

 

Module 1
Generally, a module is a file, which can be imported directly using import. Module files include ". py", ". pyo", ". pyc", ". pyd", ". so", and ". dll ".

2. package
Generally, a package is always a directory. You can use the import package or from + import to import some modules in the package. The first file in the package directory is _ init _. py. Then there are some module files and subdirectories. If there are also _ init _. py in the subdirectory, It is the sub-package of this package.

 

Reference: http://wiki.woodpecker.org.cn/moin/PythonEssentialRef8

 

Module 1
You can use the import Statement to import a source code file as a module. For example:

# File: spam. py
A = 37 # a Variable
Def foo: # A Function
Print "I'm foo"
Class bar: # A class
Def grok (self ):
Print "I'm bar. grok"
B = bar () # create an instance

Use the import spam statement to import the file as a module. When importing a module, the system must do the following:
1. Create a namespace for the objects defined in the source code file. Through this namespace, you can access the functions and variables defined in the module.

2. Execute the source code file in the new namespace.

3. Create an object named the source code file. This object references the module namespace, so that you can access functions and variables in the module through this object, such:

Import spam # import and run the module spam
Print spam. a # attributes of the access module spam
Spam. foo ()
C = spam. bar ()
...

You can use commas to separate the module names to import multiple modules at the same time:
When importing the import socket, OS, and regex modules, you can use the as keyword to change the name of the referenced object of the module:

Import OS as system
Import socket as net, thread as threads
System. chdir ("..")
Net. gethostname ()

You can use the from statement to directly import objects in the module to the current namespace. the from statement does not create a reference object to the module namespace, but directly puts one or more objects of the imported module into the current namespace:

From socket import gethostname
# Put gethostname as the current namespace
Print gethostname () # direct call
Socket. gethostname () # exception NameError: socket

The from Statement supports comma-separated objects. You can also use an asterisk (*) to represent all objects starting with an underscore in the module:

From socket import gethostname, socket
From socket import * # Load all objects to the current namespace

 

However, if a module has a list of _ all __, the from module import * statement can only import objects in the list of _ all.

# Module: foo. py
_ All _ = ['bar', 'spam'] # define objects that can be imported using '*'

 

In addition, as can be used together with from:

From socket import gethostname as hostname
H = hostname ()

 

The import statement can be used anywhere in the program. You can import the same module multiple times, but the code in the module * is only executed when the module is imported for the first time. The following import statement simply creates a reference to the module namespace. The sys. modules dictionary stores the ing between the module names of all imported modules and the module objects. This dictionary is used to determine whether to use the import Statement to import the latest copy of a module.
The from module import * statement can only be used at the top level of a module. * Note *: The from statement cannot be used in functions due to scope conflicts.
Each module has the _ name _ attribute. It is a string whose content is the module name. The top-level module name is _ main __. in command line or interactive mode, the program runs in the _ main _ module. using the _ name _ attribute, we can make the same program behave differently in different scenarios (executed separately or imported), as shown below:

# Check whether the task is executed independently or imported

If _ name _ = '_ main __':
# Yes
Statements
Else:
# No (may be imported as a module)
Statements

 

Module search path
When importing the module, the interpreter searches for the sys. path list, which contains a series 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-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 indicates the current directory. To add a new search path, you only need to add this path to this list.

 

Module import and assembly
So far, the modules described in this chapter are all text files containing Python source code. However, the modules are not limited to this. There are four types of modules that can be imported by import statements:
• Programs written in Python (. py files)

• C or C ++ extensions (compiled as shared library or DLL files)

• Package (including multiple modules)

• Built-in modules (written in C and linked to the Python Interpreter)

When querying module foo, the interpreter searches for the following files in the directory order in the sys. path list (the directory is also a type of file ):
1. define it as the directory foo of a package

2. foo. so, foomodule. so, foomodule. sl, or foomodule. dll (Compiled extension)

3. foo. pyo (only when the-O or-OO option is used)

4. foo. pyc

5. foo. py

 

For. py file. When a module is imported for the first time, it is compiled into bytecode and written into a file with the same name. pyc file. later import operations will directly read. pyc file instead. py file. (Unless. the modification date of The py file is updated, which will be generated again. pyc file) when the interpreter uses the-O option, the extension is. pyo files with the same name are used. although the content of the pyo file removes the row number, assertions, and bytecode of other debugging information, it is smaller and faster to run. if you use the-OO option to replace-O, the document string is also created. pyo files are also ignored.
If all the paths provided by sys. path fail to be searched, the interpreter will continue searching in the internal module. If it fails again, an ImportError exception will be thrown.
Compilation of. pyc and. pyo files only when the import Statement is executed.
When an import statement is used to search for a file, the file name is case sensitive. This is true even on a file system that is case insensitive (Windows, etc.). In this way, import foo only imports the file foo. py instead of FOO. PY.

 

Re-import module
If you update a module that has been imported using the 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

After reload () is run, all operations on the module will use the new import Code. However, reload () does not update the objects created using the old module, therefore, objects of the new and old versions may coexist. * Note * modules compiled using C or C ++ cannot be re-imported using the reload () function. Remember one principle. Do not use the reload () function unless it is during debugging and development.

 

Second pack
Multiple closely related modules should be organized into a package for maintenance and use. This technology can effectively avoid namespace conflicts. Create a folder named "package name" and create a _ init _. py file under the folder to define a package. You can store resource files, compiled extensions, and sub-packages in this folder as needed. For example, a package may 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 modules in the package in the following ways:
* Import Graphics. Primitive. fill import module Graphics. Primitive. fill. You can only use the full name to access module attributes, such as Graphics. Primitive. fill. floodfill (img, x, y, color ).
* From Graphics. Primitive import fill import module fill. You can only use fill. attribute name to access module attributes, such as fill. floodfill (img, x, y, color ).
* From Graphics. primitive. fill import floodfill import module fill, and put the function floodfill into the current namespace to directly access the imported attributes, such as floodfill (img, x, y, color ).


No matter which part of a package is imported, in the file _ init __. all the code in py will run. the content of this file can be blank, but it is usually used to store the initialization code of the package. All _ init _ encountered during the import process __. all py files are running. therefore, import Graphics. primitive. the fill statement runs _ init _ in the Graphics and Primitive folders sequentially __. py file.


The following statement is ambiguous:
From Graphics. Primitive import *
The original intention of this statement is to convert Graphics. all modules in the Primitive package are imported to the current namespace. however, because different platforms have different file name rules (such as case sensitivity issues), Python cannot correctly determine which modules are to be imported. this statement only runs _ init _ in the Graphics and Primitive folders sequentially __. py file. to solve this problem, _ init _ in the Primitive folder __. define a list named all in py, for example:
# Graphics/Primitive/_ init _. py
_ All _ = ["lines", "text", "fill",...]

In this way, the preceding statement can be used to import all modules in the list.


The following statement only executes the _ init _. py file in the Graphics directory, and does not import any modules:
Import Graphics
Graphics. Primitive. fill. floodfill (img, x, y, color) # failed!

However, since the import Graphics statement runs the _ init _. py file in the Graphics directory, we can solve this problem by using the following methods:
# Graphics/_ init _. py
Import Primitive, Graph2d, Graph3d

# Graphics/Primitive/_ init _. py
Import lines, fill, text ,...

In this way, the import Graphics statement can import all sub-modules (only the full name can be used to access the attributes of these modules ).


3. sys. path and sys. modules

Sys. path contains the module search path;

Sys. modules contains dict (including builtin modules) of all modules loaded before );

============================

 

 

The file import function of Python is similar to the include function of PHP, but it should be more like the require in PHP, because the import in Python cannot be executed as long as the target does not exist. To include files in the directory, you only need to set the correct path in PHP. Python is different. Let's take a look at this example.

Directory structure:

A. py: import the B. py file under the dir directory. The a. py code is as follows:

Copy the Code as follows:
# Coding = UTF-8
"B. py file under the import dir directory"
 
Import dir. B
 
Print dir. B. name


An error is returned when a. py is executed.

 

The system prompts that the module name dir. B cannot be found. By searching for official documents, we found that a _ init _. py file must be declared under the directory to contain files, even if the file is empty. Of course, this file can also initialize some data.

Create the _ init _. py file under dir. The directory structure is as follows:

Execute a. py again. Everything is OK!

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.