PythonNewbie
PythonNewbie

Reputation: 1163

How to pass variables from variables.py as a global value

Question, A friend of mine recommended:

just make a "variables.py". put a dict in there then on your code, do import variables and then variables.mydict because it direcets it to the GIL namespace and it'll be shard across all

I tried to follow his tip and I did something simple as:

first.py

def function():
    out_file = dict()
    return out_file

second.py

import first

val = first.function()
print(val) #first run should be empty, next run after restarting the script it should print "hello" ?
val["testing"] = "hello"
print(val)

Expected result:

First run should be {} and then "{'testing': 'hello'}" Next time I run the script again (Closing second.py and then re-open it again) should print: "{'testing': 'hello'}" and "{'testing': 'hello'}" again because of the two prints

Actual result:

It starts by printing {} and then "{'testing': 'hello'}" and if I re-launch the script it prints out the same "{'testing': 'hello'}" - Like the variable doesn't get saved somehow?

Shouldn't the first run when I run it be empty then on next run if I run the script again it should be "hello"?

Upvotes: 0

Views: 36

Answers (1)

Shufi123
Shufi123

Reputation: 233

According to the comment you left, your problem is this - whenever the program stops running any variable created will delete itself (It won't ever stay). Although you're importing another file, that does nothing in relation to the saving of the variables. If you need to save the values themselves (and since you're using dictionaries) I would advies you look into the Json module in Python. It allows you to save data to a file and then later load the data.

Upvotes: 1

Related Questions