Python modules and packages (bottom)

Source: Internet
Author: User

1. What is a package

#官网解释

Packages is a-structuring Python ' s module namespace by using "dotted module names"

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

#具体的: The package is a folder containing __init__.py files, so we created the package in order to organize files/modules with folders.

#需要强调的是:

1. In Python3, even if there is no __init__.py file under the package, import package will still not error, and in Python2, the package must have the file, or import packet error

2. The purpose of creating the package is not to run, but to be imported to use, remember that the package is just a form of the module, the essence of the package is a module

2, why to use the package

The essence of a package is a folder, so the only function of the folder is to organize the files.

As we write more and more, we can't put all of our functions into a single file, so we use modules to organize functions, and as we get more and more modules, we need to organize the module files in a folder to improve the structure and maintainability of the program.

3. Precautions

#1, the import statements related to packages are also divided into import 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. But for import, there is no such restriction when it is used, and the left side of the point can be a package, a module, a function, a class (both of which can call their own properties in a point-and-click manner).

Example: Import spam.x

Before importing: Import spam.x: If Spam is a module, it will be an error, spam must be a package

After import: Spam.x directly calls the X property under module spam

#2 ,Import imports the 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

The calling package is the __init__.py file under the Execute Package

Modules with the same name under the #3, Package A, and package B do not conflict, such as A.A and B.A from two namespaces

4. Example

Example 1:

glance/#top-level package├──__init__. py#Initialize the Glance package├──api#Subpackage for API Packet│├──__init__. Py│├──policy.py│└──versions.py├──cmd#subpackage for cmd small package│├──__init__. Py│└──manage.py└──db#subpackage for DB small package├──__init__. py└──models.py
directory Structure
#policy.pydefget ():Print('From policy.py')#versions.pydefcreate_resource (conf):Print('From version.py:', conf)#manage.pydefMain ():Print('From manage.py')#models.pydefRegister_models (engine):Print('From models.py:', Engine) package contains the contents of the file
File Contents
 from Import API # tell the module that calls the glance package, find the API, and start looking for the API from under your own Sys.path glance .
Glance package __init__ file Contents
#print (' from API init.py ')#__all__=[' x ', ' y ', ' policy '] # all method corresponds#x=1#y=2 from.ImportPolicy#tell the module that imported the API package (test) to find the policy and start looking for it from his own Sys.path .#Import Policy#Absolute Import#tell the module that imported the API package (test), to find the policy, from his own sys.path under the Glance.api start to find#From GLANCE.API Import Policy#Relative Import#start looking for the policy module from the current directory#From . Import Policy#help test find the Manage module#From .. CMD Import Manage#running this file directly will cause an error,#systemerror:parent module ' not loaded, cannot perform relative import#The parent module is not loaded and does not use relative import meaning#the module inside the package should not run directly as a separate file
API Package __init__ file contents
#Example 1: Importing a module directly from the import package mode#Import Glance.api.policy # Importing the policy module under the API package under the Blance package#glance.api.policy.get () # Execute the Get method under policy#Example 2: A more intuitive use#From GLANCE.API Import Policy # from the big package. Packet Import Module#Policy.get ()#From glance.api Import Policy.get # cannot be used, reported syntaxerror:invalid syntax syntax error#get ()#From glance import Api.policy#while satisfying the point to the left is the package, but here is the from ... import,import must be clear of something that cannot be brought .#It is important to note that the module imported from after import must be a definite one cannot bring something, otherwise there will be a syntax error#For example: from a import B.C is the error syntax#the init file for the API#From GLANCE.API Import Policy#when the package is imported, only the init file under the API package is executed#Policy.get ()#* The meaning of#From glance.api Import *#importing the package will still execute the init file, but here the * does not represent all the modules under the API package#* refers to the properties contained within the __all__ in Init under the API, which can be any, module, variable, etc.#Import GLANCE.API # Imports package executes glance and API package init file#print (Glance.api.policy)#But the policy is still not, because this is just importing the package, executing init, not triggering the All method#Import GLANCE.API # init file under the trigger API#print (glance.api.policy) # Importerror:no module named ' Policy '#There is an import policy under init#first from the memory to find the policy, and then from the inside of the search, and finally from the current test is located in the Sys.path to find the policy module, can not find, error#let the API pack help me find the Manage module#Glance.api.manage.main ()ImportGlanceglance.api.policy.get ()#If you are importing the GLACNE under the AAA package with the "package" peer, you will first find the parent directory of both, and then start looking from the parent directoryImportOSImportSysbase_dir= Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))Print(Base_dir)#Parent Directorysys.path.append (Base_dir) fromAaa.glance.apiImportPolicypolicy.get ()
files similar to glance test.py

Example 2:

if __name__= ='__main__'#  means to use    print as a script ('ok')

If we are directly executing a. py file, the file then "__name__ = = ' __main__ '" is true, but if we import the file through import from another. py file, then __name__ The value is the name of our py file, not the __main__.

This feature also has a use: When debugging code, in "if __name__ = = ' __main__ '" to add some of our debugging code, we can let the external module calls do not execute our debugging code, but if we want to troubleshoot the problem, directly execute the module file, Debug your code to work!

logger.pydeflogging ():Print('OK') mian.py fromCoreImportLoggerdefMain (): Logger.logging ()#print (__name__)if __name__=='__main__': Main () bin.pyImportOs,sysbase_dir=os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))#add an absolute path to an ATM#print (Base_dir)Sys.path.append (Base_dir)#Add the path to the system environment variable fromCoreImportMainmain.main ()
Example

Phenomenon:

1, when the execution of bin.py will show OK, normal operation, separate execution main.py normal display an OK

2, when main.py annotated if __name__ = = ' __main__ ', execution bin.py will show two ok, separate execution main.py normal display an OK

3, when main.py only print (__name__), execute bin.py Show only main, perform main.py display __main__

Conclusion:

1:if __name__ = = ' __main__ ' is used for debugging purposes, calling the module in other places does not execute the code under the If __name__ = = = ' __main__ ' under the called Module

2: Execute the program under the called module, will execute if __name__ = = ' __main__ ' under the code, because it is their own place, convenient debugging

5, the package of 2 ways to call

logger.py File Contents

def logger ():     Print ('logger')

# from WEB.WEB2 Import Logger # two-tier directory

Call the Logger method in the Logger module

Logger.logger ()

# from Web.web2.logger Import Logger # Call the Logger method of the Logger module under the WEB2 package under the Web package, directly with logger ()

Call the Logger method directly in the Logger module

Logger ()

.

Python modules and packages (bottom)

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.