1

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.

2
  • I would suggest going through the inspect module: docs.python.org/3/library/inspect.html maybe you'll find it helpful :) Commented Dec 23, 2020 at 6:35
  • 1
    Python source code is not the right place to store dynamic data. Use a JSON file or similar! Commented Dec 23, 2020 at 6:38

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.