Python dynamic variable loading example

Source: Internet
Author: User
This article mainly introduces the python dynamic variable loading example. For more information, see. after a program is started, all program files will be loaded into the memory, in this way, if the program text changes again, it will not affect the running of the current program, which is a protection for the program.

However, for languages like python, we sometimes use the form of "from module import variable name". if this variable is directly defined in the file, these variables are defined and assigned values at the beginning of the program, and the value remains unchanged during running. If you want to rewrite this module during running, the changed variable value cannot be used.

To solve this problem, you can define the variables in this module in the function, and the function is dynamically executed when the program is running, in this way, the latest value of the variable can be obtained. The following is an example:

First, if the function is not used:

The code is 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

In this way, when test1.py is executed, the result is still 'Hello world' instead of 'Hello you', indicating that the variable has been loaded into the memory, this module file has been overwritten on the hard disk.

Next, use the function:

The code is 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

In this way, the print result is hello you, because the function is run first, and then the variable is obtained through the function, so that the new value is 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.