Python dynamic import and changing a variable

1.4k Views Asked by At

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.

1

There are 1 best solutions below

1
On BEST ANSWER

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