How to set shared global variables between two files

Viewed 25

I have some files with the following structures. I would like to set device in train.py so the change reflects in eval.py but it doesn't and it probably execute common.py independently. I prefer not to import none common files in each other. However, I may import eval in train to do evaluation after train.

What is the solution or best practice for my scenario?

common.py

device = "cpu"

train.py

from common import *
from eval import *
import click
@click.command()
@click.argument("dev", type=str)
def train(dev):
   global device
   device = dev
   eval()

if __name__ == "__main__":
    train() # it prints "cpu"

eval.py

from common import *

def eval():
   print(device) # I expect to have 'cuda' here 

Now

$ python train.py cuda
$ cpu
1 Answers

To make this "just work", I think you need to change common.py like so:

global device = "cpu"

I'm not 100% clear on what you're trying to achieve, but seems like a default value for click might be what you ACTUALLY want to do.

However, Python's FAQ recommends that the canonical way to solve this is with a config file.

Regarding "best practices", a few other things could be improved here:

  1. eval is a Python keyword, so you should really avoid using it as a file name.
  2. Star imports (from x import *) aren't the best, as well, as they might cause name-clash issues. See this SO question for details.
Related