0
# config.py
white = (255,255,255)

# main.py
import config
print(white)

# output:
Traceback (most recent call last):
  File "C:\...\Test\Test2.py", line 2, in <module>
    print(white)
NameError: name 'white' is not defined

Process finished with exit code 1

# wanted output
(255, 255, 255)
 
Process finished with exit code 0

Hello

I want to create a variable in a config.py file, import that file into main.py, and use the variable. But the variable does not become available in main.py. I don't want to change the variable inside main.py, I only want to reference to it. What am I doing wrong?

The code provided is a simplification of the actual code and acts as an example.

One solution I can find is the following. But what shall I do if I have got multiple variables?

# main.py
import config
white_new = config.white
print(white_new)
3
  • 3
    import config.py would raise an error. Please always provide a minimal reproducible example But assuming you actually did import config, then why did you expect to be able to print(white)? You would need to use config.white. Which is probably what you should use Commented Nov 15, 2022 at 22:24
  • 2
    "But what shall I do if I have got multiple variables?" you should just use config.whatever. You could also use a from config import <list of variable> or even from config import *, but the latter is considered a bad practice. Really, just using import config and config.white, config.yellow or whatever is the best way Commented Nov 15, 2022 at 22:31
  • 1
    Your solution is right. Commented Nov 15, 2022 at 22:32

1 Answer 1

1

Just do:

# main.py
from config import white
print(white)

For multiple variables:

from config import white, variable_1, variable_2, ...
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.