Python Modules and Packages

Source: Internet
Author: User
Tags define function function definition

One, Module 1, what is a module?

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, a C or C + + extension that has been compiled as a shared library or DLL

3, Package a set of modules

4, built-in module with c written and linked to the Python interpreter

2, why use a 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, and 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. At this point, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the function of reuse

3, how to use the module? 3.1 Import

Sample files: Custom module my_module.py, file name my_module.py, module name My_module

#my_module.pyPrint('From the my_module.py') Money=1000defread1 ():Print('My_module->read1->money', Money)defread2 ():Print('My_module->read2 calling Read1') Read1 ()defChange ():Global Money Money=0
My_module Module3.1.1

A module can contain definitions of executable statements and 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, the Python 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 " "
demo.py


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.

3.1.2

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

# Test One: Money does not conflict with My_module.money # demo.py Import My_modulemoney=10print(my_module.money)" execution Result: from the my_module.py1000  " "
Test One: Money does not conflict with My_module.money
# Test Two: Read1 and My_module.read1 do not conflict # demo.py Import My_module def read1 ():     Print ('========') my_module.read1 () " " execution Result: from the My_module.pymy_module->read1->money " "
Test Two: Read1 and My_module.read1 do not conflict
# Test Three: Global variables to perform the My_module.change () operation money is still in My_module # demo.py Import My_modulemoney=1my_module.change ()print(money)' execution result: from The my_module.py1 '
Test Three: Global variables to perform the My_module.change () operation money is still in My_module3.1.3

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 the module in the newly created namespace, see initial import My_module

hint: What exactly did you do when you imported the module? In  fact function definitions is also ' statements ' that is ' executed '; the execution of a module inch Global symbol table. In fact, the function definition is also "executed" statement, module level function definition execution will put the function name into the module global namespace table, with Globals () can view

3. Create a name My_module to reference this namespace

There is no difference between this name and the variable name, it is ' first class ', and the My_module. Name is used to access the name defined in the my_module.py file, My_module. Name and test.py name from two completely different places.
3.1.4

Alias the module, 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 () copy Code
Example Usage 1

Demonstration Usage II:

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, for example:

if ' XML ' :      Import XmlReader as Reader elif ' CSV ' :      Import Csvreader as Readerdata=reader.read_date (filename)
Example Usage 23.1.5

Bring multiple modules in a row

Import # not recommended, does not conform to PEP 8

3.2 From ... import ... 3.2.1

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 import from the From statement will also create a new namespace, but import the My_module name directly into the current namespace, and in the current name namespace, simply use the name.

 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" "
View Code


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 Code3.2.2

also supports as

 from Import Read1 as read
3.2.3

also supports importing multiple lines

 from Import (Read1, read2, Money)
3.2.4

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> ' '
View Code

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

3.2.5 module-to-cycle application issues

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

3.2.6 Module Loading and modification

For performance reasons, each module is imported only once, put into the dictionary sys.modules, if you change the contents of the module, you must restart the program, Python does not support reloading or uninstalling the previously imported modules,

Some students may think of removing a module directly from Sys.modules can not be uninstalled, note that you deleted the Sys.modules module object may still be referenced by other program components, and therefore will not be cleared.

In particular, we refer to a class in this module, which produces many objects with this class, so that these objects have references to this module.

If it's just a module that you want to test interactively, use importlib.reload (), e.g. import importlib; Importlib.reload (ModuleName), which can only be used for test environments.

def func1 ():     Print ('func1')
aa.py
Import Time,importlib Import AA Time.sleep (a) # importlib.reload (aa)aa.func1 ()
Test Code

In 20 seconds of waiting time, modify the contents of func1 in aa.py, waiting for the result of test.py.

Open importlib comments, re-test

???? Not completed

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.