Python Module and package learning

Source: Internet
Author: User

Module Introduction

Python is composed of a series of modules, each module is a py suffix file, and the module is also a namespace, thus avoiding the problem of variable name conflict. Module we can understand as Lib library, if you need to use a module in a function or object, you want to import this module can be used, in addition to the system's default module (built-in functions) do not need to import outside.

Import uses the following syntax directly : Import module name (do not. py suffix)

Once the import is successful, you can use the function or object of the imported module in another module.

For example, create a Com.homer.python module in the F:\Pro-files\workspace\myPython directory: module_1.py:

[Python]View Plaincopyprint?
    1. #-*-Coding:utf-8-*-
    2. "'module_1.py '
    3. Name = "Ithomer"
    4. url = "http://blog.ithomer.net"

The first line above is to specify the encoding format, because Python is processed by default in ASCII encoding, so it is not possible to process non-English language, by specifying the encoding can achieve the internationalization effect, that is, to allow Chinese comments. The second line is the comment information, annotated with "'. Then, we go through the F:\Pro-files\workspace\myPython\com\homer directory into the python command-line mode, so that the current directory can be used as a working directory, so we can find the Module_1 this module successfully, As follows:

[Python]View Plaincopyprint?
    1. : \pro-files\workspace\mypython\com\homer>python
    2. Python 3.3. 3 (v3. 3.3:c3896275c0f6, Nov :(+) [MSC v. Max bit (AMD64)] on Win32
    3. Type "Help", "copyright", "credits" or "license" for more information.
    4. >>>

At this point, if we enter print directly (URL), the system will error, the URL variable is undefined:

[Python]View Plaincopyprint?
    1. >>> print (URL)
    2. Traceback (most recent):
    3. File "<stdin>", line 1, in <module>
    4. Nameerror:name ' url ' is not defined
    5. >>>

So we need to import the content of Module_1 to define the URL variable, but note that the variables of the imported module are not defined in the top-level namespace, but in the namespace of the module, so the following methods are used to import the following print variables:

[Python]View Plaincopyprint?
    1. >>> Import Module_1
    2. >>> Print (module_1.url)
    3. Http://blog.ithomer.net

If the print (URL) is used directly, errors that are not defined by the URL are still reported because of the namespace problem mentioned above. If you want to use the variable directly in the top-level namespace, you can use the following import method:

[Python]View Plaincopyprint?
    1. >>> from module_1 import URL
    2. >>> print (URL)
    3. Http://blog.ithomer.net

This allows the URL variables in the Module_1 module to be imported into the top-level namespace, and the direct use of variables will not be an error. Of course we can also rename the imported variable, and rename the URL to Myurl as follows:

[Python]View Plaincopyprint?
    1. >>> from module_1 import URL as Myurl
    2. >>> Print (myurl)
    3. Http://blog.ithomer.net

This allows the value of the URL to be assigned to the Myurl variable, because the From...import statement is used, so the variable is bound to the top-level namespace, and we can use the variable name directly.

It is important to note whether you use the import or the From: Import the way the module is imported, is actually telling the Python interpreter to load the specified module and executing all the statements in the module, so if there is a print-like statement in the module, we will also see the output of these statements during the import process.

For each module's import, the Python interpreter is imported only once, even if the import and From...import statements are reused, and only if PVM detects that the module is not imported. Even if later you modified the source code of the module, but did not restart the Pvm,python interpreter is still using the previously imported content in processing. If you need to reload the modified source code, one is to exit the Python interactive mode and then enter, and the second is to directly use the reload statement, as follows:

[Python]View Plaincopyprint?
    1. >>> from imp import reload
    2. >>> Reload (module_1)
    3. <module ' module_1 ' from '. \\module_1.py ' >

We can see that the system is prompted to reload the source file of the Module_1 module, and after we have modified the content, we can use this method to re-import and then execute it to see the modified content.

Module Import and execution

Modules act as basic units in the Python language and can be used to write common library functions or objects for reuse. At the same time, the module can also be run as a standalone file, previously mentioned, as long as the module file is imported, then PVM will execute all the statements in the module file. This article mainly introduces some of the steps used in the module, first defines a module module_2.py, the content is as follows:

[Python]View Plaincopyprint?
  1. #-*-Encoding:utf-8-*-
  2. "'module_2.py module content '
  3. Print (__name__)
  4. def sum (A, B):
  5. return a+b
  6. if __name__ = = "__main__":
  7. Import SYS
  8. print (sys.argv[0])
  9. a = Int (sys.argv[1])
  10. b = Int (sys.argv[2])
  11. Print (sum (A, b))

The above code basically contains the content of this article to say:

__name__ Variable Description

__NAME__ is a global variable that is used inside the module to identify the name of the module. In the example above, there is a statement that prints the __name__ variable, for example, we can see the following results when we perform the import in Python's interactive mode:

    1. >>>import module_2
    2. Module_2

As you can see, after importing the module by using import, the printed __name__ value is the name of the module we just said. In addition, if the module is executed directly through the Python interpreter, the __name__ will be set to the __MAIN__ string value as follows:

[Python]View Plaincopyprint?
    1. F:\pro-files\workspace\mypython\com\homer>python module_2.py 2 3
    2. __main__
    3. module_2.py
    4. 5

We directly execute module_2 This module file through the Windows command line, we can see the result input as above, the printed __name__ value is __main__. With this feature, we can use a module file as a common Lib library for other modules, but also as a top-level execution of the file execution, but the use of different ways.

1, when used as Lib library, only need to import the module in other modules using imports (module_2)

2, as the execution of the module, through the Python interpreter directly run the module, and then in the module file last write the above example of the if sentence segment can be (__main__)

It is very similar to the main function in Java that the __name__ variable is used to distinguish between executing a module or importing a module, but the other is the contract method name in Java, and the contract in Python is the variable name.

Parameter passing

Parameter passing mainly refers to the parameters that need to be passed as the execution module, and the use of one execution module pass parameter through the Python interpreter is as follows:

F:\pro-files\workspace\mypython\com\homer>python module name (contains. py suffix) parameter 1 parameter 2 parameter 3 ....

For the example given above, the execution is:

[Python]View Plaincopyprint?
    1. F:\pro-files\workspace\mypython\com\homer>python module_2.py 2 3
    2. __main__
    3. module_2.py
    4. 5

The Python interpreter stores all passed parameters in the SYS.ARGV list, and all parameters are treated as strings. At the same time, even if no arguments are passed, a default parameter sys.argv[0] identifies the name of the current module (such as module_2.py), so the parameters we use are all starting with sys.argv[1], and the subscript 1 represents the first passed argument, and so on (for example, 2 3).

Module packages and search paths

A python file is a module that uses a separate namespace, but it is clearly not enough to use modules to define Python functionality in practice. Because a large system of thousands of tens of thousands of modules is a normal thing, if all together is obviously not good management and there is a possibility of naming conflicts, so Python also appeared a concept of a package.

package , a way to create a Python module namespace by using the Point module name. For example, the module name A.B represents a sub-module named B under a package named A. Just like using modules to keep authors of different modules from worrying about each other's global variable names (conflicts), the Point module name lets the author of a multi-module package do not have to worry about the module name (conflict) of each other. The representation of a module package in a file system is a collection of directories that form the hierarchical structure of the module package through the hierarchical structure of the directory, and the final module file is located in the final directory. For example, define a simple module under Package pkg, then perform the following steps:

1, create a directory under the F:\Pro-files\workspace\ directory, the name is Mypython

2, under the Mypython set up the package Com.homer, and in the project directory Mypython/com/homer under the COM and com.homer respectively create __init__.py module, the content is empty can

3, in the Mypython/com/homer directory to create a Python module module_3.py, the contents are as follows:

[Python]View Plaincopyprint?
    1. #-*-Encoding:utf-8-*-
    2. "'pkg.module_3.py module content '
    3. Print ("Hello World")
    4. Def func1 ():
    5. Print ("This is Funciton one")

Note The 2nd step, you must set up a __init__.py module in each package directory, this is the Python rule, to tell the Python interpreter to use the directory as a content package, that is, the directory is a package containing the Python module. This is necessary, if not specified, we will report the following error when we import the module_3.py module in Python's interactive mode:

[Python]View Plaincopyprint?
    1. >>> from com.homer import module_3
    2. Traceback (most recent):
    3. File "<stdin>", line 1, in <module>
    4. Importerror:no module named Pkg.module_3

Therefore, the __init__.py module under the package directory is required, but the content is optional, can be empty content, can write some code or for other purposes. PVM will be piloted into the __init__.py module under this package when importing the module under a package, for example, we add content to the __init__.py module:

    1. Print ("This is __init__ module")

Then, when you re-import the package in interactive mode, the output looks like this:

[Python]View Plaincopyprint?
    1. >>> from com.homer import module_3
    2. This is __init__ module
    3. Hello World
    4. >>>

It can be seen that PVM first loads the __init__.py module and then the other modules in the directory are found and loaded.

Module search paths in Python

When a module is imported, PVM searches the module from a series of paths in the background with the following search process:

1, in the current directory search for the module;

2. In the list of paths specified in the environment variable pythonpath, search sequentially;

3. Search in the Python installation path

In fact, PVM searches through the path contained in the variable Sys.path, the list of paths contained in the variable is the path information mentioned above, and we can print to see which paths are included in the sys.pth:

[Python]View Plaincopyprint?
    1. >>> Import sys
    2. >>> Print (Sys.path)
    3. [', ' c:\\windows\\system32\\python33.zip ', ' f:\\pro-files\\python33\\dlls ', ' f:\\pro-files\\ Python33\\lib ', ' f:\\pro-files\\python33 ', ' f:\\pro-files
    4. \\Python33\\lib\\site-packages ']
    5. >>>

The path information displayed on different machines may not be the same, but at least the 3 points mentioned above are included. Knowing this path search rule, we can easily add some directories dynamically to the search path, such as the e-disk set up a Python module module_4.py, the content is as follows:

[Python]View Plaincopyprint?
    1. #-*-Coding:utf-8-*-
    2. "'pkg.module_4.py '
    3. Print ("Hello World")
    4. Print (2 * * 2)

Then perform the import in interactive mode:

[Python]View Plaincopyprint?
    1. >>> Import Module_4
    2. Traceback (most recent):
    3. File "<stdin>", line 1, in <module>
    4. Importerror:no module named Module_4

The error is expected because the F-disk is not in the search path of the Python module, and we dynamically add the path to the search module and then perform the import:

[Python]View Plaincopyprint?
  1. >>> Import sys
  2. >>> sys.path.append ("F:\Pro-files\workspace\myPython")
  3. >>> Print (Sys.path)
  4. [', ' c:\\windows\\system32\\python33.zip ', ' f:\\pro-files\\python33\\dlls ', ' f:\\pro-files\\ Python33\\lib ', ' f:\\pro-files\\python33 ', ' f:\\pro-files
  5. \\Python33\\lib\\site-packages', ' F:\\pro-files\\workspace\\mypython ']
  6. >>> from com.homer import module_4
  7. This is __init__ module
  8. Hello World
  9. 4
  10. >>>

The first is the addition of the F-packing directory in Sys.path as the search path Sys.path.append ("F:\Pro-files\workspace\myPython"), The subsequent print can see that it has indeed been added to the Sys.path, and then the import will normally import the module and execute the statements in the module. Of course, the newly added search path through the interactive mode is only valid in the current interactive mode, and once exited, it is invalidated. Therefore, we can set the PYTHONPATH environment variable according to the 2nd step of the search path rule can satisfy the different use situation can find the module.

from:http://blog.csdn.net/ithomer/article/details/17277833

Python Module and package learning

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.