Reputation: 163
I am quite new to python but I have been given some code by a group project teammate that I need to integrate with my own code. The main programme is contained in a main.py file which imports variables from a settings.py file. main.py also imports functions from functions.py file. functions.py also imports variables from settings.py. My own code requires iteration so I need to be able to change the settings.py variables when running main.py to solve the problem. Ideally I can find a way to adjust my teammates code to become a function that I can simply pass variables into and out of.
I have tried to import variables from main.py to settings.py but that results in cyclic importing. I can't find any solutions and not for lack of trying and would really appreciate any help.
main.py
import settings
import function
settings.x=10
print(settings.x+function.y)
settings.py
x=1
function.py
import settings
y= settings.x
Effectively I want this to print out 20 and not 11.
Upvotes: 1
Views: 99
Reputation: 31319
As mentioned, you can use import settings
to import settings.py
, but it sounds like you're planning to (ab)use a code file as a data file.
If the goal is to allow for changing settings quickly between runs, or even to modify the data over the course of multiple iterations, you should absolutely consider using a different file format for the settings.
A good option would be using .json
. For example:
main.py:
import json
settings = json.load(open('settings.json'))
print(settings)
settings.json:
{
"some_setting": 1,
"some_list": ["a", "b", "c"],
"nested_stuff": {
"message": "Hello World!"
}
}
Note that a .json
file looks a lot like a Python dictionary, but you need to use double quotes and there are some other specific restrictions.
Using json
is especially convenient if you want to update the file from your code as well, for example:
import json
with open('settings.json') as f:
settings = json.load(f)
settings['some_setting'] += 1
with open('settings.json', 'w') as f:
json.dump(settings, f)
Upvotes: 2