简体   繁体   中英

How to change the value of a variable in a function from a different file in Python?

I have two files, say file1 and file2. I want to be able to edit the value of a variable (epoch) from file1 in file2, but it is in the main() function in file1.

File1.py

def main(): 
  global epoch
  epoch=1
  train(args, model, device, train_loader, optimizer, epoch)

File2.py

global epoch

var = imageClassifier.main()
epochMenu = Menu(middleFrame)
subEpochMenu = Menu(epochMenu)
epochMenu.add_cascade(label="epoch", menu=subEpochMenu)
subEpochMenu.add_command(Label="1", command=imageClassifier.main(epoch == 
1))
subEpochMenu.add_command(Label="5", command=var.epoch == 5)

Please ignore my menu settings, I have been trying to get this bit working firt as it is more important.

From Python's FAQ :

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

config.py:

 x = 0 # Default value of the 'x' configuration setting 

mod.py:

 import config config.x = 1 

main.py:

 import config import mod print(config.x) 

In your case, this means you need to:

  1. Create a file config.py :

     epoch = 1 
  2. Modify file1.py :

     import config def main(): train(args, model, device, train_loader, optimizer, config.epoch) 
  3. Modify file2.py :

     import config ... subEpochMenu.add_command(Label="1", command=imageClassifier.main(config.epoch == 1)) 

One way, is by reading it from an outsource file. File1.py can access the file and write into it.

So, under File1.py you will have the following:

import json

dct = {"epoch": 7}
with open('config.json', 'w') as cf:
    json.dump(dct, cf)

And File2.py can read from that .json .

So, under File2.py you will have the following:

with open('config.json', 'r') as cf:
    config = json.load(cf)

epoch = config['epoch']
print(epoch)
# 7

I think this is the better way to do it as you decouple the modules and having a more maintainable and salable code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM