Differences between import, reload ,__ import _ in python ,__ import_python

Source: Internet
Author: User

Differences between import, reload ,__ import _ in python ,__ import_python

Import
Purpose:
Import/introduce a python standard module, including the. py file and the directory with the _ init _. py file.
E. g:

import module_name[,module1,...]  from module import *|child[,child1,...]  

Note:
When the import Statement is repeatedly used, the specified module is not reloaded, but the memory address of the module is referenced to the local variable environment.
Test:

A. py #! /Usr/bin/env python # encoding: UTF-8 import OS print 'in A', id (OS) m. py #! /Usr/bin/env python # encoding: UTF-8 import a # The first time the statement import OS In a is printed # After the OS is imported again, its memory address is the same as that in, therefore, the local reference to the OS is print 'in C'. The id (OS) import a # statement in a is not printed for the second time, because the statement in a is not reloaded.

Reload
Purpose:
Reload a loaded module. It is generally used in special situations such as the original module changes. Before reload, the module must have been imported.
E. g:
Import OS
Reload (OS)
Note:
Reload will re-load the loaded modules, but the old modules will still be used for the original instances, and the new modules will be used for the new production instances; the original memory address is used after reload; from is not supported .. Import .. Format.
Test:

A. py #! /Usr/bin/env python # encoding: UTF-8 import OS print 'in A', id (OS) m. py #! /Usr/bin/env python # encoding: UTF-8 import a # The first import will print the print id (a) statement in a # The original memory address reload (a) of) # The second reload will print the statement in a because the print id (a) is reloaded. # The memory address of a after reload is the same as the original one.

Extension:
As mentioned above, the reload function is used in special cases. In addition to the modifications made to the original module File, what else do I need to use the reload function? Here is an example.

#! /Usr/bin/env python # encoding: UTF-8 import sys # reference the sys module. This is not the first time that sys loads reload (sys) # reload sys. setdefaultencoding ('utf8') # Call the setdefaultencoding Function

The above code is correct, and then test the following code

#!/usr/bin/env python    #encoding: utf-8  import sys     sys.setdefaultencoding('utf8')   

The above test will fail. Why do we have to reload the sys module once before calling setdefaultencoding? Because the import statement here is not the first import Statement of sys, that is to say, it may be the second or third import of the sys module. Here it is just a reference to sys, only reload can be used for re-loading. Why is it necessary to re-load the function, but it cannot be called after direct reference? Because the setdefaultencoding function is deleted after it is called by the system, it is no longer available when it is referenced through import. Therefore, the sys module must be reloaded once so that setdefaultencoding can be available, in order to modify the interpreter's current character encoding in the code. Try the following code and an error will also be reported:

#! /Usr/bin/env python # encoding: UTF-8 import sys reload (sys) sys. setdefaultencoding ('utf8') del sys. setdefaultencoding # Delete the original setdefaultencoding function sys. setdefaultencoding ('gb2312 ')

So who has previously imported sys and called the setdefaultencoding function? The answer is in the Lib folder of the python installation directory, which is called site. in The py file [python2.6], you can find main () --> setencoding () --> sys. setdefaultencoding (encoding), because this site. py is automatically loaded every time the python interpreter is started, so the main function is executed every time, and the setdefaultencoding function is deleted once it comes out.

_ Import __
Purpose:
The same function as the import Statement, but _ import _ is a function that only receives strings as parameters, so its functions can be imagined. In fact, the import Statement calls this function for import. import sys <=> sys = _ import _ ('sys ')
E. g:

_ Import _ (module_name [, globals [, locals [, fromlist]) # The optional parameters are globals (), locals (), and [] by default.
_ Import _ ('OS ')
_ Import _ ('OS', globals (), locals (), ['path', 'pip ']) # equivalent to from OS import path, pip

Note:

This function can be used for dynamic loading. For example, if you want to load the modules used in a folder, but the module name under it will change frequently, you can use this function to dynamically load all modules. The most common scenario is the support of plug-in functions.

Extension:
Since the module can be dynamically imported using strings, can the module be dynamically reloaded using strings? Try reload ('OS') and report an error directly. Isn't there any other way? Although reload is not allowed, you can first unimport a module, and then _ import _ to re-load the module. Now let's take a look at how the unimport operation is implemented. In the python explanation, you can use globals (), locals (), vars (), dir () function to view the loaded modules and their locations in the current environment, but these can only be viewed and cannot be deleted, so they cannot be unimport; however, there is also a place dedicated to storing modules, this is sys. modules, through sys. modules can view all the loaded and successful modules, and there are more than globals. This means that some additional modules will be loaded by default, and then unimport will be added.

#! /Usr/bin/env python # encoding: UTF-8 import sys _ import _ ('A') # The first import will print the message del sys. modules ['a'] # unimport _ import _ ('A') # re-import will print the message, because unimport has been run once _ import _ ('A') # The message will not be printed this time.

Import is called _ import __

If you do not know the name of the module to be imported and need to store the module name in the string variable, you can only use _ import _ def getfuncbymodule (module_name, func_name ): try: module = _ import _ (module_name) return getattr (module, func_name) Partition t ImportError as e: pass print getfuncbymodule ("string", "split ") ("a B c") in addition, if the module File name you write has a-compliant, such as a my-mod.py, then using import my-mod won't run, but the following statement can: __import _ ("my-mod") can also use the following statement: exec ("import my-mod ")

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.