Matty Tranmer
Matty Tranmer

Reputation: 21

How to change and save variable in different files

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.

Upvotes: 2

Views: 897

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191691

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)
    

Upvotes: 3

FMARAD
FMARAD

Reputation: 101

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.

Upvotes: 1

Related Questions