How does python overload module instance resolve

  • 2020-07-21 09:10:35
  • OfStack

This paper first introduced the concept of module in Python, mentioned that a module is usually composed of multiple modules, and then analyzed the relevant content of module overload through specific examples, detailed introduction is as follows.

Modules are one of the core concepts of Python program architecture. Larger programs are often presented in the form of multiple module files, with one module designed as a master file or top-level file to launch the entire Python program. Each Python source file with the.py suffix is a module whose contents can be read by other files through "import". In a general sense, a module is an encapsulation of variable names. For example, write a module test. py, which contains two variable names name and age.


name='Aidan' 
age=27 

Then, execute the following command from the Python command line


import test 
print(test.name, test.age) 

The result is Aidan 27

The function dir(modelname) can be used to get the variable names available within the module, containing 1 of the built-in Python variable names such as' ___, 27EN__'.
An Python program is often composed of multiple modules connected via import. Each module file is a namespace, and variable names for other module files are not visible unless that file is imported via import or via import from model import varible Import a variable. This avoids variable naming conflicts, as each module is a separate namespace, similar to the C language for 1 function and its local variables.

Essentially, an "import" is a command to load the contents of one file into another so that the other file can be used in the outside world import name.py . An import is only effective the first time it is executed per session, but it is not effective when the same file is imported multiple times, even if the file changes, because the file is compiled into bytecode the first time it is imported. The import module must know the detailed path of the module (file search, you can specify all directories to search through the PYTHONPATH variable in sys.path), so for simplicity, put all files that need to be imported in the same directory.

If you want to run the same file multiple times in the same session (or if the file has changed and must be reloaded), you need to call the "overload" function -ES44en (name). Make sure that the module has been successfully imported through import before calling the reload function. See the difference between "function" reload() and "statement" import, reload() is a function, the parameter is the imported file module file name, import is a statement, do not need parentheses. Python's overload feature allows users to edit and improve code modules during interactions, so to ensure that you are running up-to-date code, use reload() first.

During flask debugging, if we make some changes to the file, the server will be restarted without having to stop the server and restart again. There is a hidden mechanism for reloading.

Here is a simple example to explain how python reloads a module

Create a new file called ES64en.py, which is very simple:


#coding=utf-8 
''''' 
Created on 2016-3-25 
 
@author: Administrator 
''' 
 
msg = 'change it ' 

Create a new file named reloaddemo.py with the following contents:


#coding=utf-8 
''''' 
Created on 2016-3-25 
 
@author: Administrator 
''' 
import threading 
import reloadsetting 
import sys,os, time 
 
 
def printworker(): 
  while True: 
    time.sleep(1) 
    print reloadsetting.msg 
   
def auto_reload(): 
  while True: 
     
    mods = ["reloadsetting"] # the need reload modules 
    
    for mod in mods: 
      try: 
        module = sys.modules[mod] 
      except: 
        continue 
       
      # Get the name of the file  
      filename = module.__file__ 
       
      #pyc The end of the file is only in the first 1 It is generated at second load time, so even if we make changes to the file, its modification time will not change during run time  
      if filename.endswith(".pyc"): 
        filename = filename.replace(".pyc", ".py") 
      # Get on file 1 The time of the revision  
      mod_time = os.path.getmtime(filename) 
      #module.__dict__  Saved in the module information, specific reference globals function  
      if not "loadtime" in module.__dict__: 
        module.loadtime = 0 # first load's time 1* 
      try: 
        # If the modification time is greater than above 1 Second load time, then reload  
        if mod_time > module.loadtime: 
          reload(module) 
      except: 
        pass 
    
      module.loadtime = mod_time 
      time.sleep(1) 
if __name__ == '__main__': 
  t_reload = threading.Thread(target=auto_reload) 
  t_reload.start() 
   
  t_reload2 = threading.Thread(target=printworker) 
  t_reload2.start() 

We started to run ES75en.py, one thread kept printing msg in reloadsetting module, and one thread kept trying to reload reloadsetting module. In the running process, modify the msg reloadsetting module content, soon, the printed content will change, you may worry that, if accidentally write when we amend the wrong code, such as give deleted msg, or written msg =, behind which there is no assignment, the overload not would have failed, this concern is unnecessary, even if there are errors in the module reloadsetting, so when the call reload function, also won't happen error, module 1 times is still effective after reload state, do not believe, you can have a try

conclusion

That's it for python how to overload module instance parsing. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: