Home  >  Article  >  Backend Development  >  Compare the usage differences of import reload __import__ in python

Compare the usage differences of import reload __import__ in python

巴扎黑
巴扎黑Original
2017-09-19 10:45:101833browse

import

Function: Import/introduce a python standard module, which includes .py files and directories with __init__.py files (custom modules).

import module_name[,module1,...]

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

Note: Use the import statement multiple times , the specified module will not be reloaded, but the memory address of the module will be referenced to the local variable environment.

Example:

pythontab.py

#!/usr/bin/env python    
#encoding: utf-8  
import os  
print 'in pythontab',id(os)

test.py

#!/usr/bin/env python    
#encoding: utf-8  
import pythontab   #第一次会打印pythontab里面的语句  
import os  #再次导入os后,其内存地址和pythontab里面的是一样的,因此这里只是对os的本地引用  
print 'in c',id(os)  
import pythontab  #第二次不会打印pythontab里面的语句,因为没有重新加载

reload

Function: Reload the loaded module Loading is generally used in special situations such as changes in the original module. The module must have been imported before reloading.

import os

reload(os)

Explanation:

reload will reload the loaded module, but the originally used instance will still be used The old module, and the newly produced instance will use the new module; after reload, the original memory address will still be used; from cannot be supported. . import. . format module is reloaded.

Example:

pythontab.py

#!/usr/bin/env python    
#encoding: utf-8  
import os  
print 'in pythontab',id(os)

test.py

#!/usr/bin/env python    
#encoding: utf-8  
import pythontab   #第一次import会打印pythontab里面的语句  
print id(pythontab) #原来pythontab的内存地址  
reload(pythontab)  #第二次reload还会打印pythontab里面的语句,因为有重新加载  
print id(pythontab) #reload后pythontab的内存地址,和原来一样

Extension:

As mentioned above, in The reload function will only be used under special circumstances; in addition to modifications to the original module file, what other situations require the use of the reload function? Here is an example.

#!/usr/bin/env python    
#encoding: utf-8  
import sys   #引用sys模块进来,并不是进行sys的第一次加载  
reload(sys)  #重新加载sys  
sys.setdefaultencoding('utf8')  ##调用setdefaultencoding函数

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

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

The above test will fail, so why must the sys module be reloaded first when calling setdefaultencoding? Because the import statement here is not actually the first import statement of sys, that is to say, this may actually be the second or third import of the sys module. This is just a reference to sys, and can only be reloaded by reload; then Why does it need to be reloaded, but the function cannot be called if it is directly referenced? Because the setdefaultencoding function is deleted after being called by the system, it is no longer there when it is referenced through import. Therefore, the sys module must be reloaded once so that setdefaultencoding will be available and the current character encoding of the interpreter can be modified in the code. Try the following code, the same error will be reported:

#!/usr/bin/env python    
#encoding: utf-8  
import sys    
reload(sys)   
sys.setdefaultencoding('utf8')    
del sys.setdefaultencoding   ##删除原来的setdefaultencoding函数     
sys.setdefaultencoding('gb2312')

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

__import__

Function:

The same function as the import statement, but __import__ is a function and only receives strings as parameters, so its function can You know it. In fact, the import statement calls this function to perform the import work. import sys 209861d5cd2975725c730f519ed6ad71sys = __import__('sys')

Use:

__import__(module_name[, globals[, locals[, fromlist]]]) #Optional parameters default to globals(), locals(),[]

__import__('os')

__import__('os',globals( ),locals(),['path','pip']) #Equivalent to from os import path, pip

Note:

This function can usually be used during dynamic loading , for example, if you want to load all modules in a folder, but the module names under it 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 modules can be dynamically imported through strings, can modules be dynamically reloaded through strings? Try reload('os') to report an error directly. Is there no other way? Although you cannot reload directly, you can unimport a module first, and then __import__ to reload the module. Now let’s see how the unimport operation is implemented. In the Python interpretation, you can view the modules loaded in the current environment and their locations through globals(), locals(), vars(), dir() and other functions, but these can only be viewed. Delete, so it cannot be unimported; however, there is another place specifically for storing modules, which is sys.modules. Through sys.modules, you can view all loaded and successful modules, and there are more than globals, indicating that the default Some additional modules will be loaded, and the next step is unimport.

#!/usr/bin/env python    
#encoding: utf-8  
import sys  
__import__('a')      #第一次导入会打印消息  
del sys.modules['a']   #unimport  
__import__('a')    #再次导入还是会打印消息,因为已经unimport一次了  
__import__('a')    #这次就不会打印消息了

The above is the detailed content of Compare the usage differences of import reload __import__ in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn