Warm tip: This article is reproduced from serverfault.com, please click

Update variable value in variables Python file

发布于 2020-12-23 06:31:08

I have a variables.py file with a key TOKEN= 123456. I need to update that value dynamically when ever it required.

The file Constants.py reads:

#!/usr/bin/env python
# encoding: utf-8
"""
variables.py
"""

TOKEN= 50

And refresh_tok.py

#!/usr/bin/env python
# encoding: utf-8
"""
refresh_tok.py
"""
import variables

def refresh_token():
    print(variables.TOKEN) // previous value 50
    change_constant(variables.TOKEN, 100)
    print(variables.TOKEN) // value I am expecting is 100 but it says 50


def change_constant(match_string, replace_string):
    read_file = open("variables.py", "rt")
    read_data = read_file.read()
    read_data = read_data.replace(match_string, replace_string)
    read_file.close()
    
    write_file = open("variables.py", "wt")
    write_file.write(read_data)
    write_file.close()

Value that I am expecting in 2nd print statement in refresh_tok.py is 100 but it is still on previous value and print 50 rather then 100.

Questioner
Zain ul Ebad
Viewed
11
juanpa.arrivillaga 2020-12-23 14:39:19

You seem to have a fundamental misunderstanding about the nature of computer programs.

Your change_constant function reads the source code from a file as a string, creates a new string which changes that source code, then writes that new string to the same file. This will never affect the module that you've loaded. This is very important to understand.

Instead, all you need to do is:

variables.TOKEN = new_value

Of course, this only affects the running process. If you need to persist these changes, then you need to choose some sort of persistence strategy, e.g. writing to a file. It is generally not a good practice to use python source code for this, instead, use some suitable serialization format, e.g. JSON, pickle, INI-like config files, YAML, etc etc (or even if it is very simple just a text file).