1

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.

3
  • 5
    How could we help without seeing your code? Commented Apr 15, 2019 at 1:51
  • 3
    "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." - Could you please elaborate on this claim more, and provide a minimal reproducible example? Your problem sounds a bit like an XY problem. Commented Apr 15, 2019 at 1:51
  • I've added some code which hopefully explains my problem better. Commented Apr 15, 2019 at 10:06

1 Answer 1

2

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