[Learn Python step by step] 10. modules and packages

Source: Internet
Author: User

1. Import Module

Any Python program can be imported as a module, as long as the Python interpreter can find the location of the defined module. Generally, when a module is imported, the Python interpreter will search by following the steps below:

  • Search for this module in the current directory
  • In the environment variablePYTHONPATHIn
  • Search for Python installation path

Based on the Python search path method, the following three methods can be used for the Python interpreter to find a custom module (excluding the module in the current directory ):

 

1.1 place the module in the default directory

The Python interpreter finds the required modules in the default directory and usessysModulepathVariable to view the directory that the interpreter finds silently, as shown below:

               

Generally, it should be stored insite-packagesDirectory, which is used to store third-party modules outside the standard library.

 

1.2 directly set the module directory in the program

Create a folder at any location to store custom modules. Here isC:/Python, Add a newHello.pyFile, the content is as follows:

 

Similarly, add the directory where the module is locatedsysModulepathYou can use the functions defined in this module:

 

 

1.3 modify Environment Variables

You can also modify the environment variables to inform the Python interpreter of the position of the custom module:

My computer --> properties --> advanced --> Environment Variables

AddPYTHONPATHVariable, used by multiple directories;Separate them as follows:

In this way, we can directly usehelloModule:

 

 

1.4 supplement: environment variable configuration in Sublime Text

If you use Sublime Text to write Python code, use the third method, that is, modifyPYTHONPATHVariable method, inCtrl+BWhen running the code, the module defined in the Declaration path in the environment variable cannot be found. This is a problem of Sublime Text itself, because no matter whether it uses the Python built-in IDLE or CMD to execute the code, both can passPYTHONPATHVariable to find the module in its declared path. If you want to use a third-party module in Sublime Text through the environment variable, You need to explicitlyPython.sublime-buildThe steps are as follows:

Preferences --> Browse Packages... --> Find the Python folder --> open the Python. sublime-build File

Add the pathenvAttribute, use multiple paths;And modify as follows:

 

 

2. Add the test code to the module.

Sometimes we need to add test code to the module to directly execute the test module to check whether the module works correctly. However, when the program is referenced by other programs as a module, the test code is not executed.__name__Variables can be easily implemented:

                 == : test()

 

3. Understand the specific content of the module

Before using a module, we should first understand the specific content of this module, which can save a lot of time and avoid writing code blindly without understanding the specific content of the module. Using the following methods can quickly create a general impression on a module.

 

3.1 Use dir

You can view the content contained in the module.dirFunction, which lists all the features of the object (all functions, classes, variables, etc.), as follows:

     publicMembers = [n  n  dir(sys)   n.startswith(   m       m+     

 

3.2 use AllVariable

__all__The variable defines the public interface of the module, as follows:

 copy.

 __all__Variable equals to the interpreter: imports all content from the module (Use*), That is, the following form:

 copy  *

You can only use__all__Defined functions. If you use__all__If there is no defined member, you only need to explicitly import it. If the imported module is not defined__all__Variable, useimport *By default, all (_.

 

3.3 view document strings

Pass__doc__Variable, we can viewrangeFunction document string:

 range.

Not every module and function has a clear document string, if you want to learn more about some modules and functions if it works, you should refer to the Python Library Reference (http://docs.python.org/2/library/index.html ), more standard and detailed information is provided here.

 

3.4 use help to get help

Compared with the document string, the help function can obtain more information, such as the function signature:

 help(copy.copy)

 

3.5 read source code

In addition to writing code by yourself, reading the source code is the best way to learn Python. To view the source code location of a module, you can:

 csv. 

The file to be queried is.pycThe file ending with the suffix. This is a bytecode file generated after processing by the Python interpreter..pyThe source file ending with the suffix.

 

4. Organization module form-Package

To further organize modules, You can group them into packages. A package is basically a type of module. When a module is stored in a file, the package is the directory where the module is located. To enable the Python interpreter to treat it as a package, it must contain__init__.pyFile (__ init__.pyIt can only be an empty file, but it can also execute the package initialization code, including setting__all__Variable ). If it is imported as a common module, the file content is the package content.

The following is a simple package layout named "drawing", which contains modules named "color" and "shapes:

C:\Python C:\Python\drawing C:\Python\drawing\.py C:\Python\drawing\colors.py C:\Python\drawing\shapes.py 

After configuring the package, you can import the package content as follows:

 drawing  drawing.colors  drawing  shapes 

 

References & further reading

Basic Python tutorial (version 2)

Http://docs.python.org/2/using/windows.html

Http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7

Http://docs.sublimetext.info/en/latest/reference/build_systems.html

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.