简体   繁体   中英

Python dynamic import and changing a variable

Lets say I have the following config file:

config.py :

x = 2
y = x * 2

I would like to import this in the file main.py , preferably using load_source command, but I also want to be able to change the value of x at the time of import such that the change in x propagates to the other variables in the config.py . For example, I want the following code, prints 6 and not 4.

main.py :

import imp
config = imp.load_source('', 'config.py')
config.x = 3
print config.y

What is the best way to do that? I know I can write functions in config.py to do this for me, but I prefer the config to be simple variable definitions only.

Put the code into a class:

class Config(object):
    def __init__(self, x=2):
        self.x = x
        self.y = x * 2

Then, in your main program:

c = Config(3)
print c.y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM