Search code examples
pythonpython-3.xglobal-variablesfile-handling

Unable to assign value to global variable inside function, Python 3.8.10


Using Python 3.8.10, I'm working on a simply python module (one .py file) with constants, functions and classes relevant to a physics course I'm currently taking. Inside this module, I have a collection of global variables of "constants", such as "g" for force of gravity near earth's surface (9.8) N/kg. I'm working on a feature to modify these constants in the case of dealing with questions that involve things like "let g = 10 N/kg". I need to incorporate reading / writing to a txt file which will store the constants, and can be modified to modify constants in the program. So I have defined a function "updateConstantsFromFile(file)" which is supposed to set all these global variables to what it reads in the file. And the crazy thing is THIS WORKS WHEN I FIRST RUN THE PROGRAM, but NOT AGAIN. I cannot understand why, I've tried many different methods of assigning global variables, none seem to work.

the function looks like this:

def updateConstantsFromFile(file):
    global g
    lines = file.readlines()
    for line in lines:
        varName = line.split()[0]
        value = line.split()[2]
        print(varName, value) #Always prints the correct variable name and value as expected
        if varName == "g":
            g = float(value)

In place of g = float(value) I've tried globals()[varName] = float(value), globals().__setitem__(varName, float(value), and consts["g"] = float(value) in which "consts" was a dictionary of my constants and this DID WORK, which i really don't understand.

Here is how I first call the function:

if __name__ == "__main__":
    try:
        constFile = open("constantsFile.txt", "r")
        updateConstantsFromFile(constFile)
        constFile.close()
    except FileNotFoundError:
        constFile = open("constantsFile.txt", "w")
        restoreDefaultConstants(constFile)
        constFile.close()

How can I update a global variable from within this function?


Solution

  • How to make global variables work in Spyder inside a function? It was an issue in Spyder. I needed to run in console's namespace instead of an empty one. Option is here: Spyder/Preferences/Run/General settings/Run

    Thanks to everybody who helped!