Python Modules and Packages

Source: Internet
Author: User
Tags define function

First, what is the module

A module is a way to organize your code, and a package is the way you organize your modules.

Common scenario: A module is a file that contains Python definitions and declarations, and the file name is the suffix of the module name plus the. Py.

In fact, the import loaded module is divided into four general categories:

1 code written using Python (. py file)

2 C or C + + extensions that have been compiled as shared libraries or DLLs

3 packages for a set of modules

4 built-in modules written and linked to the Python interpreter using C

Second, why to use the module

If you quit the Python interpreter and then re-enter, then the functions or variables you defined previously will be lost, so we usually write the program to a file so that it can be persisted and executed in Python test.py when needed, when test.py is called a scripting script.

With the development of the program, more and more functions, in order to facilitate management, we usually divide the program into a file, so that the structure of the program is clearer and easier to manage. In this case, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the reuse of functionality,

Third, how to use the module

Import XX Module name

1. The module can contain definitions of executable statements and functions that are intended to initialize the module,

2. They are only executed when the module name is first encountered importing import statements (import statements can be used anywhere in the program and are imported multiple times for the same module, in order to prevent you from repeating the import, Python's optimization means that the module name is loaded into memory after the first import, and the subsequent import statement only adds a reference to the module object that has loaded the large memory, does not re-execute the statements within the module, as follows:

# demo.py Import # The my_module.py code is executed only on the first import, where the explicit effect is to print only once ' from the my_module.py ', and of course the other top-level code is executed, except that it does not show the effect. Import My_module Import My_module Import My_module " " execution Result: from the my_module.py " "
multiple import, will only be executed once

We can find the module that is currently loaded from Sys.modules, Sys.modules is a dictionary that contains the mapping of the module name to the module object, which determines whether the import module needs to be re-imported.

Each module is a separate namespace, defined in this module of the function, the namespace of the module as the global namespace, so that when we write our own module, we do not have to worry about our definition in our own module global variables will be imported, and the user's global variables conflict

If the module is imported for the first time, it will be loaded and executed. I ' I

Summary: Three things to do when importing module my_module for the first time:

1. Create a new namespace for the source file (My_module module), which is the namespace that is accessed when the functions and methods defined in My_module are used in global.

2. Execute the code contained in Module 7 in the newly created namespace, see initial import My_module

3. Create a name My_module to reference this namespace

Module Alias

Alias for module name, equivalent to M1=1;M2=M1

Import My_module as SM 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 ()
same mode of operation, unified code

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 ' XML ' :      Import XmlReader as Reader elif ' CSV ' :      Import Csvreader as Readerdata=reader.read_date (filename)
View Code From ... import ...

Comparing the import My_module, the namespace ' my_module ' of the source file is brought into the current namespace, and must be my_module when used. The way of the name

The FROM statement is equivalent to import, and a new namespace is created, but the name in the My_module is imported directly into the current namespace, and the name is used directly in the current namespace.

 from Import Read1,read2

This way, it is good to use READ1 and read2 directly at the current location, while executing, still with the my_module.py file global namespace

#Test One: Import the function read1, still go back to my_module.py in search of the global variable money#demo.py fromMy_moduleImportRead1money=1000Read1 ()" "execution Result: from the My_module.pyspam->read1->money" "#Test Two: Import function read2, call READ1 () when executing, still return to my_module.py for Read1 ()#demo.py fromMy_moduleImportread2defread1 ():Print('==========') read2 ()" "execution Result: from the my_module.pymy_module->read2 calling Read1my_module->read1->money" "
Call Read1 directly

If there is a duplicate name read1 or read2, then there will be an overlay effect.

# Test Three: The imported function read1 is overwritten by the read1 defined by the current location. # demo.py  from Import Read1 def read1 ():     Print ('==========') read1 () " " execution Result: from the my_module.py========== " "
View Code

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

 from Import Money,read1money # binds the name money of the current location to the Print # Print the current name # read the name money in my_module.py, still for " " From the My_module.py100my_module->read1->money " "
View CodeFrom ... import *

From my_module Import * All names in my_module that are not preceded by an underscore (_) are imported into the current location, and 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.py1000<function read1 at 0x1012e8158><function read2 at 0x1012e81e0>< function change at 0x1012e8268> ' '

Add a line to the my_module.py

__all__=['money ','read1'#  This allows you to import the two names specified in the list by using the From My_module Import * In another file.

* 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. can only be imported in the __all__ list.

Circular reference problems for modules

Think: If there are two modules, a, B. Can I import b in the A module and import a in the B module?

Python Modules and Packages

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.