Python 2.7 Learning notes modules and packages

Source: Internet
Author: User
Tags pprint

Let's consider some of the following scenarios:

1, write a Python program, if the program is relatively simple, you can put the code in a python file. However, if the program is more functional, multiple Python files may be needed to organize the source code. The code between these files must be associated, such as Python code in one file calling a function defined in another Python file.

2, we write the program, certainly not all things are written by themselves, not all the wheel, we will definitely use some of the standard Python provided by the library. How do you use it? In fact, the previous article has been seen, with the import statement. The using statement is used in import,c# as in Java.

3, we want to write a common code, or from the outside to find a third-party public code, how to put into the entire Python system, how to be used by their own code.

These are the things that are common in writing programs.

These problems, Python is solved through the mechanism of modules and packages.

simply put, a module is a Python file, and a package contains a set of modules. let's take a practical example to illustrate this.

I. Case 1: One of the simplest examples

Write the test1.py file with the following code

# Coding=utf-8 Import test2 Print " Hello " Test2.fun ("World")

Write the test2.py file with the following code

# Coding=utf-8 def Fun (para):     Print para

The two Python files are in the same directory, but not necessarily in the relevant system directory of Python, and can be any legal directory.

When we execute test1.py, we can run it successfully.
It can be seen that the code in the test1.py called the fun method in test2.py, which is the key to the call in the test1.py import test2 This statement, that will test2.py this module introduced,

Called at the same time by the module name. function name.

Ii. Case 2: How to place the module

In the above example, two Python files are located in the same directory. What if test2.py want to put it in another directory?

The key here is for the Python interpreter to find test2.py.

This is common, for example, test2.py is a generic module that can be used by multiple programs, and it cannot be put together with programs that use it, or it will copy multiple copies.

There are several ways to put test2.py in other places, as described below.

Method One: Put in Python's existing system directory

Put the module (Python file) in the Python system directory, and when the module is introduced, the Python interpreter can find it.

You can see which system directories are currently available through the following code:

>>>ImportSys,pprint>>>Pprint.pprint (sys.path) ["', 'C:\\python27\\lib\\site-packages\\pip-7.1.2-py2.7.egg', 'C:\\python27\\lib\\site-packages\\paramiko-1.15.2-py2.7.egg', 'C:\\python27\\lib\\site-packages\\robotframework_sshlibrary-2.1.1-py2.7.egg', 'C:\\python27\\lib\\site-packages\\ecdsa-0.13-py2.7.egg', 'C:\\python27\\lib\\site-packages\\selenium-2.47.1-py2.7.egg', 'C:\\python27\\lib\\site-packages\\decorator-4.0.2-py2.7.egg', 'C:\\python27\\lib\\site-packages\\easyprocess-0.1.9-py2.7.egg', 'C:\\python27\\lib\\site-packages\\webtest-2.0.20-py2.7.egg', 'C:\\python27\\lib\\site-packages\\beautifulsoup4-4.4.1-py2.7.egg', 'C:\\python27\\lib\\site-packages\\waitress-0.8.10-py2.7.egg', 'C:\\python27\\lib\\site-packages\\webob-1.5.1-py2.7.egg', 'C:\\python27\\lib\\site-packages\\six-1.10.0-py2.7.egg', 'C:\\python27\\lib\\site-packages\\jsonpointer-1.10-py2.7.egg', 'C:\\python27\\lib\\site-packages\\jsonpatch-1.12-py2.7.egg', 'C:\\windows\\system32\\python27.zip', 'C:\\python27\\dlls', 'C:\\python27\\lib', 'C:\\python27\\lib\\plat-win', 'C:\\PYTHON27\\LIB\\LIB-TK', 'c:\\python27', 'c:\\python27\\lib\\site-packages', 'C:\\python27\\lib\\site-packages\\win32', 'C:\\python27\\lib\\site-packages\\win32\\lib', 'C:\\python27\\lib\\site-packages\\pythonwin']

The path object in the standard library SYS module of Python contains all the system paths, using the Pprint method in the Pprint module to format the displayed data, and if you use the built-in statement print, you can only display all of the content on one line, which is inconvenient to see.
We just need to put the Python file (test2.py in this example) in any of these directories, and the Python interpreter can find it.

Note: Must be placed directly in the above directory, can not create subdirectories, placed in sub-directory. To be able to put in sub-directory, is the concept of package, described below.

Method Two: New system directory

In addition to Python's own default system directories, applications can add system directories through code.

Because the system path exists under the Sys.path object, the Path object is a list in which you can insert the directory yourself through code, such as

Sys.path.append ("D:/demo/python/dir")

However, it is clear that the inserted directory is only valid for the current program as a system directory because it is only in memory.

Method Three: Set environment variables

If we do not want to put the code in the Python system directory, so as not to mix with the Python directory, increase the complexity of management.

Even sometimes, because of permissions, it is not possible to add files in the Python system directory.

and want to put in the directory of their own planning. At this point the operating system's PYTHONPATH environment variable can be searched by the Python interpreter for all directories even under the environment variable.

So that we can put the code into the directory contained in the PYTHONPATH environment variable, it can be import by another program.

Setting the PYTHONPATH environment variable is a relatively good way to recommend it.

Case three: Priority of the path

According to the above introduction, a module to be able to other program reference (import) to, and the program can be placed in a directory, can be placed in the Python system directory, can be placed in the PYTHONPATH environment variable contained in the directory, which is the highest priority.

At this point we can test, write three files with the same name, a function with the same name defined in the file, the function has only one print statement, but the contents of the three files in the print statement of the function is different.

Then write another program import the above file, and call the defined function, look at the output, you know the priority.

After testing, it is found that the priority level from high to the bottom is:

1) Current directory

2) environment variable Pythonpath contains the path

3) Python system directory

This is also very well understood, normal situation, the more the user's setting priority is higher.

Case FOUR: Package

As we described above, each module is a separate python file. In order for Python to find them, it must be placed in the appropriate directory.

Without layering, it is easy to create naming conflicts and management confusion.

Especially in the actual situation, a function is often composed of multiple modules (files), generally we want to put the code in a directory, easy to manage.

This is going to use Python's package mechanism.

Python's package, which is physically a directory, is actually a module, but rather a special module, which can also contain other modules.

For example, let's say:

We create a directory, such as Testpackage

To make this directory a Python package, you need to create a file __init__.py in that directory, with two consecutive underscores before and after the Init.

Content such as:

# Coding=utf-8 Print " hello,i am Package " def Hello ():     Print " Good "

We will then create a test.py file in the directory where the Testpackage is located, with the following

# Coding=utf-8 Import Testpackagetestpackage.hello ()

The testpackage is imported in test.py, when we execute the test.py, we find the output:
Hello,i am Package
Good

As can be seen, Testpackage is a special module, but because it is not a Python file, but a directory, then it is the __init__.py of the module is the contents of the import package, is actually imported __init__.py file. The common module corresponds to a python file, which requires the same module name and file name.

We then set up two files under Testpackage, module1.py, module2.py, the contents are:

# Coding=utf-8 def fun1 ():     Print " Module1 "
# Coding=utf-8 def fun2 ():     Print " Module2 "

Let's use these two modules to modify the test.py file. The contents of the modified test.py are as follows:

# Coding=utf-8 Import Testpackage Import Testpackage.module1  from Import Module2testpackage.hello () testpackage.module1.fun1 () module2.fun2 ( )

The output of the execution test.py is as follows:
Hello,i am Package
Good
Module1
Module2

Let's analyze the contents of the test.py below.

As you can see, we have imported the Module1 module and the Module2 module in two different ways.

Using the import Testpackage.module1 method requires a full path reference, such as TESTPACKAGE.MODULE1.FUN1 (), when using functions in Module1.

With the From Testpackage import module2, it is required to omit the package name reference, such as module2.fun2 () when using functions in Module2.

In general, we use the from import approach.

It is also important to note that importing a module in a package eliminates the need to import the package, because the package is automatically imported, which means that the package's __init__.py file is automatically imported.

Another point, since the package is a special module, its storage and ordinary modules, it can be used with its program in a directory, can be in the Python system directory, can also be placed in the environment variable Pythonpath included in the directory.

With the package this function, for the complex program, you can better organize the source code.

Case five: What can I put in the module?

In the previous example, some of the content has been involved, the following we will be more detailed introduction of what can be put in the module, how to use the problem.

First, what can be put in the module, in theory, like ordinary Python code files, you can put variables, function definitions, class definitions, and even direct statement calls.

According to the truth, except for the python file that was executed, the other Python files are modules.

Second, use the question. The first thing to be imported.

When imported, statements written directly in the module, such as print, are executed immediately, and variables are defined and initialized (if any).

Python 2.7 Learning notes 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.