Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truly Global Variable in python

OK so the project I am working on requires* using a truly global variable (or five) and the other questions on here have to do with cross module variables (could be helpful later just not yet).

Here is my problem: I have a program that will be running an environmental simulation and I need to set some global variables to be used and modified inside some of the functions. How would one go about doing that?

*When I say require I mean that I haven't found a more efficient way to do this.

like image 779
unknown Avatar asked Sep 29 '22 11:09

unknown


1 Answers

Yes, there is a way to use and modify global variables inside functions that are spread across several modules. Put the variables in a module and import that module into your main program:

# globals.py
klaatu = "Once in Persia reigned a king ..."

 

# main_program.py
import globals

def modify_klaatu():
    print globals.klaatu
    globals.klaatu = "It was the best of times, it was the worst of times."
like image 197
Robᵩ Avatar answered Oct 02 '22 16:10

Robᵩ