Python dynamic load variable sample sharing

Source: Internet
Author: User
As we all know, after the program starts, each program file will be loaded into memory, so if the program text changes again, to the current program operation has no effect, this is a program is a protection.

However, for languages like python that interpret execution, we sometimes use the "from module import variable name" form, if the variable is directly defined in the file, then these variables will be defined at the beginning of the program, assigned value, the value of the operation process is unchanged. If the module is intended to be rewritten during the run, the changed value of the variable cannot be used.

For this problem, you can change the way the variables in this module are defined in the function, and the function is executed dynamically when the program is running, so that you can get the latest value of the variable. Here is an example:

First, no function is used:

Copy the Code code as follows:


#model1. py
P_hello = ' Hello world! '

#test1. py
From Model1 import P_hello
File = open (' model1.py ', ' W ')
File.write ("P_hello = '%s! '"% (' Hello you '))
File.close ()
Print P_hello

Thus, when executing the test1.py, the result is still ' Hello World ', not ' hello you ', stating that the variable has been loaded into memory, although the module's file has been rewritten on the hard disk.

Next, use the function's case:

Copy the Code code as follows:


#model1. py
def rule ():
P_hello = ' Hello world! '
Return locals ()

#test1. py
From model1 Import rule
File = open (' model1.py ', ' W ')
File.write (' Def rule (): \ n ')
File.write ("P_hello = '%s! ') \ n "% (' Hello you '))
File.write ("return locals () \ n")
File.close ()
P_hello = Rule () [' P_hello ']
Print P_hello

So, the result of print is Hello you, because at run time, the function is executed first, and then through the function to obtain the variable, so that the new value will be obtained.

  • 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.