"Python3 Module and package import"

Source: Internet
Author: User
Tags define function

One, module import 1. Definition

The Python module, which is a python file that ends with a. Py, contains Python object definitions and Python statements.

Modules allow you to logically organize your Python code snippets.

Assigning the relevant code to a module will make your code better and easier to understand.

Modules can define functions, classes, and variables, and modules can also contain executable code.

Include: Built-in modules, custom modules, third-party modules;

2. Role

The greatest benefit is that the maintainability of the code is greatly improved. Second, writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python built-in modules and modules from third parties.

The use of modules also avoids conflicting function names and variable names. Functions and variables of the same name can exist in different modules individually, so we do not have to think about names that conflict with other modules when we write our own modules. But also be aware that try not to conflict with the built-in function name.

3. Import

Once the module is well defined, we can use the import statement to introduce the module with the following syntax:

Import module1[, module2[,... Modulen]

Cases:

#spam. Pyprint (' from the spam.py ') Money=1000def read1 ():    print (' Spam->read1->money ', Money) def read2 ():    print (' spam->read2 calling read ')    read1 () def change ():    Global Money    money=0

Import Module

Import spam #只在第一次导入时才执行spam. py inside the code, the explicit effect here is to print only once ' from the spam.py ', of course, the other top-level code is also executed, but did not show the effect.
Execution result: from the spam.py

Note: A module can contain executable statements and definitions of functions that are intended to initialize modules that execute only when the module name is first encountered when importing an import statement (the import statement can be used anywhere in the program and is imported multiple times for the same module. To prevent you from repeating the import, Python is optimized by loading the module name into memory after the first import, followed by an import statement that only adds a reference to the module object that has loaded the large memory, and does not re-execute the statements within the module.

Import importing module What to do:
1. Create a new namespace
2. Execute the code for the file with the new namespace as the global namespace
3. Get a module name spam, point to spam.py generated namespace

    • Test one: Money does not conflict with Spam.money
#测试一: Money and Spam.money do not conflict #test.pyimport spam money=10print (Spam.money) ' execution result: from the spam.py1000 '

    • Test two: Read1 and spam.read1 do not conflict
#测试二: Read1 and Spam.read1 do not conflict #test.pyimport spamdef read1 ():    print (' ======== ') spam.read1 () ' Execution result: from the Spam.pyspam->read1->money 1000 "

    • Test three: Global variables to perform the Spam.change () operation money is still money in spam
#测试三: Global variable that performs the Spam.change () operation money is still the result of #test.pyimport Spammoney=1spam.change () print (money) ' execution in spam: from the Spam.py1 ""

    • As, alias for module name
Import spam as SM  #sm为spam的别名 print (Sm.money)

Cases:

The way you alias an imported module is useful for writing extensible code, assuming there are two modules xmlreader.py and csvreader.py that define function read_data (filename): Used to read some data from a file, However, different input formats are used. You can write code to selectively select read modules, such as

if File_format = = ' xml ':     import xmlreader as readerelif File_format = = ' csv ':    import Csvreader as Readerdata=reade R.read_date (filename)

    • Importing multiple modules on a single line
Import Sys,os,re

4.from...import
From ModName import name1[, name2[, ... Namen]]

To import the Fibonacci function of the module FIB, use the following statement:

From fib import Fibonacci

This declaration does not import the entire FIB module into the current namespace, it only introduces the Fibonacci individual in the FIB to the global symbol table of the module that executes the declaration.

From ... import: Import module What to do:

1. Create a new namespace
2. Execute the code for the file with the new namespace as the global namespace
3. Direct access is the name of the spam.py generated namespace

#测试一: Imported function read1, execution still back to spam.py for global variables money#test.pyfrom spam import read1money=1000read1 () "' Execution result: from the Spam.pyspam->read1->money "#测试二: Imported function read2, need to call READ1 () when executing, still return to spam.py to find Read1 () #test. Pyfrom Spam Import Read2def read1 ():    print (' ========== ') read2 () "Execution result: from the spam.pyspam->read2 calling Readspam-> Read1->money 1000 "

However, if there is currently duplicate name Read1 or read2, then there will be coverage effect.

#测试三: Imported function Read1, Read1 overridden by the current location definition #test.pyfrom spam import read1def read1 ():    print (' ========== ') read1 () ' Execution result: From the spam.py========== '

One particular point to note is that variable assignment in Python is not a storage operation, but a binding relationship, as follows:

From spam import money,read1money=100 #将当前位置的名字money绑定到了100print (Money) #打印当前的名字read1 () #读取spam. PY name Money, still 1000 ' "From the Spam.py100spam->read1->money 1000"

From ... import ...
Advantages: Convenient, no prefix added
Cons: Easy to conflict with the name space of the current file

    • From ... import ... also supports as and imports multiple modules
From spam import read1 as readfrom spam import (Read1,                  read2, Money                  )

    • From spam import *

Import all names in spam that are not preceded by an underscore (_) to the current location, and in most cases our Python program should not use this type of import, because * you do not know what name you import, it is likely to overwrite your previously defined name. And the readability is extremely poor, there is no problem when importing in an interactive environment.

From spam import * #将模块spam中所有的名字都导入到当前名称空间print ("Money") print (read1) print (read2) print (change) "Execution result: from the Spam.py1000<function read1 at 0x1012e8158><function read2 @ 0x1012e81e0><function Change at 0x1012e8268 > "

    • __all__ to control * (to release the new version)

Add a line to the spam.py

__all__=[' money ', ' read1 '] #这样在另外一个文件中用from spam import * This can import two names specified in the list

    • __name__

spam.py as script execution, __name__= ' __main__ '
spam.py as module import, __name__= module name

Function: Used to control the. py file to perform different logic in different scenarios

#fib. Pydef fib (n):    # write Fibonacci series up to n    A, b = 0, 1 while    b < n:        print (b, end= ")        A, b = B, a+b    print () def fib2 (n):   # return Fibonacci series up to n    result = []    A, b = 0, 1 while    b < n :        result.append (b)        A, B = B, a+b    return resultif __name__ = = "__main__":    import sys    fib (int ( SYS.ARGV[1]))

Perform

#python fib.py <arguments>python fib.py #在命令行

5. Search Path of the module

The order in which the modules are found is: modules that are loaded in memory, built-in modules->sys.path paths

The Python interpreter automatically loads some modules at startup and can be viewed using sys.modules, which, when importing a module for the first time (such as spam), first checks whether the module has been loaded into memory (the memory that corresponds to the current execution file's namespace), and, if so, a direct reference

If not, the interpreter looks for the built-in module with the same name, and then looks for the spam.py file from the list of directories given by Sys.path if it is not already found.

In particular, the custom module name should not be the same as the system built-in module.

After initialization, the Python program can modify the Sys.path, and the path is placed prior to the standard library being loaded.

Note: The search is based on the left-to-right order in Sys.path, the first priority is found, the Sys.path may also contain. zip archive files and. Egg files, Python will treat. zip archive as a directory

#首先制作归档文件: Zip module.zip foo.py bar.pyimport syssys.path.append (' module.zip ') import foo,bar# You can also use the exact location of the directory structure in the zip sys.path.append (' Module.zip/lib/python ')

Note: The path under Windows does not start with R and will be syntactically incorrect

Path under Windows does not start with R, syntax error Sys.path.insert (0,r ' C:\Users\Administrator\PycharmProjects\a ')

Ii. Import of packages 1. Definition

A package is a way to organize the Python module namespace by using the '. Module name '.

Whether it's in import or From...import form, it's the first time to be alert when you encounter a dot in an imported statement (rather than in use): This is the import syntax for packages. The left side must be a package;

A package is a hierarchical file directory structure that defines a Python application environment consisting of a module and a sub-package, and a sub-package under a sub-package. In a nutshell, a package is a folder, but a __init__.py file must exist under the folder, and the contents of the file can be empty. __int__.py is used to identify the current folder as a package.

A package is a collection of modules that are made up of a series. A module is a collection of functions and classes that handle a class of problems.

Cases:

glance/                   #Top-level package├──__init__.py      #Initialize The Glance package├──api                  #Subpackage for api│   ├──__init__.py│   ├──policy.py│   └──versions.py├──cmd                #Subpackage for cmd│   ├──__init__.py│   └── Manage.py└──db                  #Subpackage for db    ├──__init__.py    └──models.py

File contents

#文件内容 #policy.pydef Get ():    print (' from policy.py ') #versions. Pydef create_resource (conf):    print (' From version.py: ', conf) #manage. Pydef Main ():    print (' from manage.py ') #models. Pydef register_models (engine):    Print (' From models.py: ', engine)

2.import

Before you use a function or class from a module, you first import the module. The import of the module uses the import statement.

When calling a function or class of a module, you need to prefix the module name.

Import file, the resulting namespace name from the file, import package, the name of the resulting namespace is also derived from the file, that is, the __init__.py under the package, the import package is the essence of the import of the file

Cases
Testing in files of the same level as the package glance

In the case of imports, the left side of the point must be a package.

3.from ... import ...

If you do not want to use prefix characters in your program, you can use From...import ... Statement to import the module.

It is important to note that the From Post import module must be clear one cannot take a point, otherwise there will be a syntax error, such as: From a import B.C is the error syntax

Cases

Testing in files of the same level as the package glance

From glance.db import modelsmodels.register_models (' MySQL ') from glance.db.models import Register_modelsregister_ Models (' MySQL ')

The current path to the executed file is Sys.path

Import Sysprint (Sys.path)

Attention:

1. Import statements related to packages are also divided into imports and from ... import ... Either way, regardless of location, you must follow a principle when importing: any point on the import, the left side must be a package, otherwise illegal. Can carry a series of points, such as Item.subitem.subsubitem, but all must follow this principle.

2. For import, there is no such restriction when used, the left side of the point can be a package, a module, a function, a class (they can all call their own properties in the way of a point).

3. Compare the application scenarios for import item and from item import name:
If we want to use name directly then we must use the latter.

4.__init__.py file

Either way, the first time the package is imported or any other part of the package, the __init__.py file under the package is executed sequentially (we can verify it by printing a line within each package's file), which can be empty, but it can also hold some code to initialize the package.

5.from GLANCE.API Import *

Import all from the package API, in fact the statement only imports the name defined in the __init__.py file under the package API, and we can define __all___ in this file:

#在__init__. PY definition x=10def func ():    print (' from api.__init.py ') __all__=[' x ', ' func ', ' policy ']

At this point we are in the glance of the files in the same class to execute from GLANCE.API import * To import the contents of the __all__ (versions still cannot import).

6. Absolute Import and relative import

The top-level package glance is for others to use, and then within the glance package will also have each other to import each other's needs, this time there are absolute import and relative import two ways:

Absolute import: Starting with glance

Relative import: With. Or. (can only be used in one package and not in different directories)

Example: We want to import glance/cmd/manage.py in glance/api/version.py

In glance/api/version.py# absolute import from Glance.cmd import Managemanage.main () #相对导入from: CMD import managemanage.main ()

Test Result: note must be tested in glance peer files

Note: You can import the built-in or third-party modules with import (already in Sys.path), but to absolutely avoid importing the submodule of the custom package using import (not in Sys.path), you should use the From ... import ... Absolute or relative import, and the relative import of the package can only be used from the form.

7. Importing packages separately

Importing package names individually does not import all of the contained sub-modules in the package, such as

#在与glance同级的test. PY Import glanceglance.cmd.manage.main () ' Execution result: attributeerror:module ' glance ' has no attribute ' CMD ""

Workaround:

#glance/__init__.pyfrom. Import cmd #glance/cmd/__init__.pyfrom. Import Manage

Perform:

#在于glance同级的test. PY Import Glanceglance.cmd.manage.main ()

Don't ask: __all__ can not solve, __all__ is used to control from...import *

Python3 module and package import

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.