Python Path---modules and packages

Source: Internet
Author: User

Modules and Packages (official website https://docs.python.org/3/contents.html) 1. Modules

1.1 A. py file (usually defined as a function or data or method) can be called as a module

The 1.2 module can contain executable statements and definitions of functions that are intended to initialize modules that are executed only when the module name is first encountered importing import statements (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.

1 #test.py2 ImportSpam#The spam.py code is executed only on the first import, where the explicit effect is to print only once ' from the spam.py ', and of course the other top-level code is executed, except that it does not show the effect.3 Importspam4 Importspam5 Importspam6 7 " "8 Execution Result:9 From the spam.pyTen " "
View Code

1.3 Each module has its own separate namespace, and the namespace defined in the module can be used as the global namespace,

The global variables of the module do not conflict with the name space of the imported module

sample file: spam.py, file name spam.py, module name spam#spam.pyPrint('From the spam.py') Money=1000defread1 ():Print('Spam->read1->money', Money)defread2 ():Print('Spam->read2 Calling Read') Read1 ()defChange ():Global Money Money=0 ... ..... ..... ..... ..... ..... ..... ..... ..... ..... ... .. ..... ............ ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ...... ..... ......................................................................................................................... ..........................................................................................11111111111111111111#test.pyImportSpam#The spam.py code is executed only on the first import, where the explicit effect is to print only once ' from the spam.py ', and of course the other top-level code is executed, except that it does not show the effect.ImportspamImportspamImportspam" "execution Result: from the spam.py" "2222222222222222222222#Test Two: Read1 and Spam.read1 do not conflict#test.pyImportspamdefread1 ():Print('========') Spam.read1 ()" "execution Result: from the Spam.pyspam->read1->money" "333333333333333333333333333#Test Three: Global variables to perform the Spam.change () operation money is still in spam#test.pyImportSpammoney=1Spam.change ()Print(Money)" "execution Result: from the Spam.py1" "

2. Import the module

Three things to do when you first import a module:

1. Create a new namespace for the source file, and the function and method defined in the module is the namespace of this module if it is used in global

2. When the module is imported, the code contained in the import module is executed, and the syntax is the name of the import+ import module

2.1 Alias for module quite m1=1,m2=m1

1 import spam as SM

2 print (Sm.money)

Demonstration Usage One:

There are two SQL modules MySQL and Oracle, depending on the user's input, choose different SQL functions

#mysql.pydefsqlparse ():Print('From MySQL sqlparse')#oracle.pydefsqlparse ():Print('From Oracle Sqlparse')#test.pyDb_type=input ('>>:')ifDb_type = ='MySQL':    ImportMySQL as DBelifDb_type = ='Oracle':    ImportOracle as Dbdb.sqlparse ()
View Code

2.1 From ... import ...

Equivalent to import, the same will be done again My_module file, also create a namespace, but from. . Import ... is to import the name in the My_module directly into the current namespace, which means that it can be called directly instead of using the My_module. Name to invoke as import .

Two ways of comparing

# Import Mode Import My_module # module name + '. ' + function name to invoke My_module.read () # From...import ... Way from import  read#  call directly with function name read ()
View Code

PS: Using From...import ... Import, typically used to specify a part of the import module, or convenient to use, there is a special import from ... import * (function is to import all the contents of the module, but there is a disadvantage)

As

from my_module import read as r

MultiRow

from my_module import (read1,                      read2,                      read3)

2.1.1from. Import * imports all names in the module that are not preceded by an underscore (_) into the current location, in most cases our Python program should not use this type of import, because * you don't know what name you import, It is likely that you will overwrite the name you have defined before. And the readability is extremely poor, there is no problem when importing in an interactive environment.

 from Import # Import all the names in the module my_module into the current namespace Print (Money) Print (READ1) Print (read2) Print (change) " " execution Result: from the my_module.py<function read1 at 0x1012e8158><function read2 at 0x1012e81e0><function Change at 0x1012e8268>' "
View Code

Add a row in the module. PY

__all__=[' money ','read1# So in another file with the From My_module import * This can import the two names specified  in the list 

* If the name in the my_module.py is pre-added _, i.e. _money, then the from my_module Import *, then _money cannot be imported

2.2 Modules Run as scripts

if __name__ = = ' __main__ '

All modules have a built-in property __name__ that can be used to view the module name

Returns ' _main_ ' When the current file executes, and returns the module name executed if it is not in the current file execution

# in my_module.py Print (__name__) # Executive my_module.py __main__ # in test.py Import My_modlue #  Execution Result: my_module
View Code

2.3 Module Search Path

The Python interpreter automatically loads some modules at startup, and you can use Sys.modules to view

When a module is first imported (such as My_module), it is first checked to see if the module has been loaded into memory (the memory that corresponds to the current execution file's namespace), and if there is a direct reference

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

So the summary module lookup order is: In memory loaded modules, built-in module->sys.path path contains modules

It is important to note that our custom module names should not be the same as the system built-in modules

It is important to note that our custom module names should not be the same as the system built-in modules

It is important to note that our custom module names should not be the same as the system built-in modules

Package

Python Path---modules and packages

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.