2
votes

I have three python files:

a.py

theVariable = "Hello!"

b.py

import a
a.theVariable = "Change"

c.py

import a

while True:
    print(a.theVariable)

I want c.py to print out "Change" instead of "Hello!". How can I do this and why wont this work? There needs to be separate files because b.py would be running a Tkinter gui.

2
c cannot print out "change" without importing and running the code in b, but even then, you're importing a twice, and not sharing the state of that variable - OneCricketeer
If you're running a GUI, please actually show your GUI code as a minimal reproducible example via an edit otherwise, the answers you get are not relevant and guesses, at best - OneCricketeer
What is the reason for trying to do this? I ask because mutating global variables like you want is a source of difficult-to-find bugs. - Code-Apprentice
btw, you don't need sockets or any network stack for this... - OneCricketeer

2 Answers

3
votes

You can use classes to get an instance variable which holds some state

a.py

class Foo():
    def __init__(self):
        self.greeting = "Hello"

And create functions so that you can defer actions on references

b.py

def changer(f):
    f.greeting = "Change"

When you import a class and then pass it to a function, you are passing a reference to something that can change state

c.py

from a import Foo
from b import changer

a = Foo()
for x in range(10):  # simple example
    if x > 5:
        changer(a)
    print(a.greeting)
    
1
votes

a.py

theVariable = "Hello!"

def change(variable):
    theVariable = variable

b.py

import a

change('change')

c.py

import a

while True:
    print(theVariable)

i've been working with PyQt recently and this worked fine. setting a function in the orgin .py file makes it much simpler.