0

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.

3
  • Why not just import config and manipulate variable like that. Either way they're global Feb 25, 2016 at 22:26
  • Even if you import it, the value of y will not change when you change x because it is defined after x, and the change of x, will not change the y, unless it is defined as a list or something
    – Amin
    Feb 25, 2016 at 22:32
  • That is not how that works. Python uses dynamic casting when you say y = x * 2 that isn't a pointer. Meaning even in the script where y was defined if you print(y) then set x = 1 and print(y) again y will be the same. you could make y a function or create a class within config like brent suggested. Feb 25, 2016 at 22:36

1 Answer 1

1

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
1
  • I was hoping I could get away without defining class or functions, but yes it works, thanks.
    – Amin
    Feb 25, 2016 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.