Python Learning Notes series----(quad) modules

Source: Internet
Author: User

This chapter mainly describes the concept of Python modules and the concept of packages, as well as their use, the harvest is also large.

When you lift a python file, you often hear 3 nouns, python scripts, python modules, Python packages. The concept of scripting is referenced from the python interactive command line, and the code snippet that runs in the command line is copied to a file, which can be called a script, there may be the same function between scripts, and so on, for one script to use a function in another script, Another script here can be called a module, that is, the definition of a module can be imported into other modules or the main module, a Python package is a way to manage the module namespace, similar to the Python module to solve the different modules of the name of the global variables, The Python package addresses the name of the module when the package consists of multiple modules.

4.1 Modules

A module is a file that contains Python definitions and declarations. The file name is the module name plus the . py suffix. Can be __name__ by the global variable can be worth to. Each module has its own private symbol table (each identifier in the program source code is bound to its declaration or usage information, such as its data type, scope, and memory address.) )。 All definitions in the module take this table as the global symbol table. So the user of this module can use global variables within this module without worrying about conflicts with the users ' global variables.

Import of 4.1.1 Modules

The import statement of the module is usually placed at the very beginning of a module, and the imported module name is placed in the global symbol table of the module that uses the module.

There are 2 ways to import modules:

A:import Modname.submodname. In this way, only packages can be imported, and only the package name of the parent package is placed in the global symbol of the module that introduced the module, that is, by importing the package in this way, if you want to use a function within the package or some variable, you need to go to the parent package and then into the symbol table inside the parent package to get those definitions

Here are 2 examples: The first example, Python has a PIP package under the installation subdirectory, the following are the sub-packages and sub-modules, and then the package is described as an example:

>>> Print dir ()
[' __builtins__ ', ' __doc__ ', ' __name__ ', ' __package__ ']
>>> Import pip
>>> Print dir ()
[' __builtins__ ', ' __doc__ ', ' __name__ ', ' __package__ ', ' Pip ']
>>> Import Pip.index
>>> Print dir ()
[' __builtins__ ', ' __doc__ ', ' __name__ ', ' __package__ ', ' Pip ']
>>> Import Pip.index.egg_info_matches
Traceback (most recent):
File "<stdin>", line 1, in <module>
Importerror:no module named Egg_info_matches

After importing the module using the import statement, the current global symbol table has more than the package name Pip; When the submodule is imported again, the global symbol table does not add the Submodule name; when attempting to import a function in a sub-file with an import statement, the module is not present.

Example 2 is the question of how to use the various definitions within the package through this type of import. Because only the package name is present in the current global symbol table after import, the method to use the submodule must pass., from package to submodule, to specific method or other definition.

# Fibonacci numbers moduledef fib (n):    # write Fibonacci series    up to n01     while B < N:        print B,        = B, A +bdef fib2 (n)   :return  Fibonacci Series up to n    = []    01while     B < N:        Result.append (b)        = B, a+    breturn result
>>>Import Fibo>>> Fibo.fib ( +)1 1 2 3 5 8  -  +  the  -  the 144 233 377 610 987>>> Fibo.fib2 ( -)[1,1,2,3,5,8, -, +, the, -, the]

B. From modname.submodname import subsubmodname or function

This method allows you to import a sub-module directly under a package, or directly into a function under a sub-module. In the example, an attempt to import a sub-file's function name after the import statement prompts for a syntax error. However, it is no problem to import sub-files or functions.

>>>print dir () ['__builtins__','__doc__','__name__','__package__']>>> fromPIP Import Index>>>print dir () ['__builtins__','__doc__','__name__','__package__','Index']>>> frompip import index.egg_info_matches File"<stdin>", line1     frompip Import index.egg_info_matches^syntaxerror:invalid Syntax>>> frompip.index Import egg_info_matches>>>print dir () ['__builtins__','__doc__','__name__','__package__','egg_info_matches','IndeX']

If you use the From PIP Import Index statement, the call is made using Index.egg_info_matches to invoke the function in index.

If you use the From Pip.index import egg_info_matches statement, you can use Egg_info_matches directly when you want to invoke the Egg_info_matches function in index. However, if you attempt to invoke other functions within the module, you will get an error.

4.1.2 Dir () function

Dir () is one of the built-in functions that lists which names are defined in the module and then returns a list string. It contains variable names, module names, function names, and so on. Use Help to see the use of Dir, you can get more small details.

Search path for the 4.1.3 module

When importing a module, how does Python search for this module? First, the parser will look for existence from within the built-in module, and if it does not, it will search from the Sys.path path, which contains the following three parts:

A. The folder containing the current file

B. Python configuration under Path

C. Python's default installation directory

The directory where the script resides is placed at the beginning of the search path, which is before the path to the standard library. This means that the script in the current directory will be loaded and will not be loaded if the module with the same name is in the library directory. This should be considered a mistake unless you are interested in replacing the standard library.

Python's Sys.path can be modified, but other files run without using the list (or the directory that was added before printing sys.path is gone).

>>> Import sys>>> sys.path.append ('/ufs/guido/lib/python')

4.1.4 Standard Module

The Python website has a document "Library Reference" is the introduction of standard modules, the standard module is a part of the module is directly built in the interpreter, using import can be used directly, the following are common:

4.2 Packs

The basic concept of the package has been mentioned in the introduction of the module, in order to allow Python to identify a directory is a Python package, you need to add the __init__.py file in the directory, the file can be empty, you can initialize the package or set __all__ parameters.

The main reason for

      Setting the _all__ parameter is: import The   statement uses the following conventions: If the &NBSP;__init__.py   The code defines a list named __all__ , and then encounters   from package  Import * statement, all the module names in this list should be imported. When a package has a new release package, it needs the package author to update the list. If the author of the package believes that it is not possible to import their package by using import *, you can also decide not to support it. __ALL__&NBSP; not defined, from a Package importing *  Statement   does not import all submodules from the package into the current namespace;

When importing a module or method, there is another way: from a package importing *, the PIP packet is tried as follows:

>>>print dir () ['__builtins__','__doc__','__name__','__package__']>>> fromPIP Import *>>>print dir () ['CommandError','Configoptionparser','frozenrequirement','insecurerequestwarning','Installationerror','Piperror','Updatingdefaultshelpformatter','__builtins__','__doc__','__name__','__package__','Absolute_import','AutoComplete','Basecommand','Baseparser','Bazaar','check_isolated','cmdoptions','commands','commands_dict','Compat','Create_main_parser','Deprecation','dist_is_editable','Download','Exceptions','get_installed_distributions','Get_prog','Get_similar_commands','get_summaries','git','Index','locale','Locations','Logger','Logging','Main','Mercurial','Models','Operations','Optparse','OS','parseopts','Pep425tags','Pip','Re','req','Status_codes','Subversion','SYS','Utils','VCs','Warnings','Wheel']

Results all the sub-packages and sub-modules under PIP are all in.

Python Learning Notes series----(quad) modules

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.