Python modules and packages (top)

Source: Internet
Author: User
Tags define function function definition naming convention

1, what is the module

Definition: A module is a file containing Python definitions and declarations (the file name is the suffix of the module name plus the. py), and the module can be used for import.

To define a module first:

#The spam.py:spam module has print statements, and when the spam module is loaded, it is parsed out to executePrint('From the spam.py') Money=1000defread1 ():Print('Spam module:', Money)defread2 ():Print('Spam module') Read1 ()defChange ():Global Money Money=0
2. Module Import method

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

#模块可以包含可执行的语句和函数的定义, the purpose of these statements is to initialize the module, which executes only when the module name is first encountered when importing the 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 been loaded into memory and does not re-execute the statements within the module, as follows

# test.py Import # 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. Import spam Import spam Import spam " " execution Result: from the spam.py " "
test.pyThe first import did three things


#1. Create a new namespace for the source file (spam module), and the functions and methods defined in spam are the namespaces that are accessed when using global.

#2. Execute the code contained in the module in the newly created namespace, see initial import spam
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-level function definition enters the function name in the module ' s global symbol table.
In fact, function definitions are also "executed" statements, and the execution of module-level function definitions puts function names into the module global namespace table, with Globals () to view
It's a little bit around, isn't it? The simple word is that the function inside the module is placed inside the current file, which is equivalent to writing a function in the current file, and loading

#3. Create a name spam to reference this namespace
There is no difference between this name and the variable name, it is ' first class ', and the spam. Name is used to access the name defined in the spam.py file, spam. Name and test.py name from two completely different places.


The imported module has a separate namespace

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.pyImportSpam Money=10Print(Spam.money)" "execution Result: from the spam.py1000" "#test.pyImportspamdefread1 ():Print('========') Spam.read1 ()" "execution Result: From the spam.py execution process::spam-> find:read1-> print: money" "#test.pyImportSpammoney=1Spam.change ()Print(Money)" "execution Result: from the Spam.py1" "
View Code


Alias for module name

How to alias a module that has already been imported is useful for writing extensible code

Import spam as SM Print (Sm.money)

Example 1: 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

Example 2: Suppose there are two modules xmlreader.py and csvreader.py, all of which define function read_data (filename): Used to read some data from a file, but in a different input format. You can write code to selectively pick the Read module

if ' XML ' :     Import XmlReader as Reader elif ' CSV ' :     Import Csvreader as Readerdata=reader.read_date (filename)
View Code


3, module import method from ... import

From spam import read1,read2

Comparison of From...import and import

#唯一的区别就是: Use From...import ... is to import the name in the spam directly into the current namespace, so in the current namespace, the name can be used directly, without prefix: spam.

#from ... import ... In a way that's good and bad.
Benefits: Easy to use
Cons: Easily conflicts with names in the current execution file

Verify one: The current location is used directly with Read1 and Read2, when executed, still with the spam.py file global namespace

#Test One: Import the function read1, still go back to spam.py in search of the global variable money#test.py fromSpamImportRead1money=1000Read1 ()" "execution Result: from the spam.py to perform:read1-> printing via:spam->: money" "#Test Two: Import function read2, call READ1 () when executing, still return to spam.py for Read1 ()#test.py fromSpamImportread2defread1 ():Print('==========') read2 ()" "execution Result: from the spam.pyspam->read2 calling Read1spam->read1->money" "
View Code

Verification Two: If there is currently duplicate name Read1 or read2, then there will be coverage effect.

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

Validation three: The imported method is always based on the source file when it is executed

 from Import Money,read1money # binds the name money of the current location to the Print # Print the current name # read the name money in spam.py, still for " " From the Spam.pyspam->read1->money " "
View Code


From ... import * all methods of calling module, try not to use, may conflict with your own definition

#大部分情况下我们的python程序不应该使用这种导入方式, because * you don't know what name you import, it's likely to overwrite the name you've already defined, and the readability is extremely poor.

 from  spam import  * Span style= "Color:rgb (0, 128, 0); >#   import all names in module spam that are not preceded by an underscore (_) into the current namespace  print   print   (READ1)  print  print   (change)   "  execution result: from the Spam.py1000<function read1 at 0x1012e8158><function read2 @ 0x1012e81e0><function Change at 0x1012e8268 > can use __all__ to control * (to release the new version), add a line of __all__=[' money ' in spam.py, ' read1 '] #这样在另外一个文件中用from spam import * This will import the two names specified in the list. 
View Code


4. Modules and Scripts

#编写好的一个python文件可以有两种用途:

A: script, a file is the entire program, used to be executed

Second: The module, the file contains a bunch of functions, used to be imported to use


#python为我们内置了全局变量__name__,

When a file is executed as a script: __name__ equals ' __main__ '

When a file is imported as a module: __name__ equals module name


#作用: Used to control the. py file to perform different logic in different scenarios

if __name__ = = ' __main__ ':

Run () # Executes the logic in the current script

#fib.pydefFIB (n):#Write Fibonacci series up to nA, b = 0, 1 whileb <N:Print(b, end=' ') A, b= B, A +bPrint()defFIB2 (n):#return Fibonacci series up to nresult =[] A, B= 0, 1 whileb <N:result.append (b) A, B= B, A +breturnresultif __name__=="__main__":    Importsys fib (int (sys.argv[1]))#execution: Python fib.py <arguments>Python fib.py 50#executing at the command line
Script Examples


5. Module Search Path

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

1, when the first import of a module (such as spam), will first check whether the module has been loaded into memory (the current execution of the file's namespace corresponds to the memory), if there is a direct reference

The Ps:python interpreter automatically loads some modules into memory at startup, and you can use Sys.modules to view

2, if not, the interpreter will find the same name of the built-in module

3. If you haven't found it, look for the spam.py file from left to right in the list of directories given by Sys.path.

#需要特别注意的是: Our custom module names should not be the same as the system built-in modules. For example: Do not customize a module called json.py

#在初始化后, the Python program can modify the Sys.path, and the path to the previous precedence over the standard library is loaded.

Import sys>>> sys.path.append ('/a/b/c/d')>>> Sys.path.insert (0,'/x/y/z'# ranked in front of the directory, preferred to be searched

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, and Python will treat. zip archives as a directory.


6. Compiling Python files

To increase the speed of loading modules, emphasis is placed on emphasizing that loading speed is not the speed of operation.

The Python interpreter caches the compiled version of each module in the __pycache__ directory, in the format: MODULE.VERSION.PYC.

The version number of Python is usually included. For example, under the CPython3.3 version, the spam.py module is cached as __PYCACHE__/SPAM.CPYTHON-33.PYC. This naming convention guarantees a multi-version coexistence of compiled results.

Python checks that the modification time of the source file is compared to the compiled version and needs to be recompiled if it expires. This is a completely automated process. And the compiled module is platform independent, so the same library can be shared between different architectures of the system, that is, PYC is a cross-platform bytecode, is executed by the Python virtual machine, but the content of PYC is related to Python version, different versions of the compiled PYC file, The 2.5 compiled PYC file cannot be executed on 3.5, and the PYc file can be deserialized, so it appears only to increase the load speed of the module, not for encryption.

.

Python modules and packages (top)

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.