I can't seem to find the right way to do this. I have a main module with a variable x
and an auxiliary module that must be able to update x
.
The following does not work:
#main.py
import aux
x=0
aux.update()
#aux.py
import main
def update():
main.x += 1
It seems to be possible with a third
module holding x
:
#main.py
import aux,third
third.x = 0
aux.update()
#aux.py
import third
def update():
third.x += 1
#third.py
x = 0
Is this third
module necessary? Is there a "better way"?
Perhaps you could write some sort of class
, make an instance of it and pass that to your update()
function:
#main.py
import aux
class Foo:
def __init__(self, x):
self.x = x
third = Foo(0)
print(third.x)
aux.update(third)
print(third.x)
#aux.py
def update(instance):
instance.x += 1
Output:
0
1