Ask coding questions

← Back to all posts
Variable from other files
bossotron13 (29)

From all the google searches I’ve been told to use, from file import Variable but when i do that, it runs all the code inside of file, and is there a way i can import all the variables not one by one. Ive tried from file import * but that just runs all the code.

Answered by JustARatherRidi (191) [earned 5 cycles]
View Answer
Commentshotnewtop
JustARatherRidi (191)

Let's say you have two files, main.py and variables.py, in the same folder.

If you write the following into variables.py and save it:

power = 9001

Then in main.py, you can write this:

import variables
print(variables.power) # 9001 gets printed

You can also do the same thing like so

from variables import power
print(power) # 9001 gets printed

If you have some code in variables.py that you don't want to run when it is imported, then you can do this:

power = 9001
if __name__ == '__main__':
    ...
    # Code in here does not run when this file is imported,
    # it only runs when the file is executed.

If variables.py looks like above, then you can import it without the ... part being run.


If there's some other issue you're running into, please put your code in a repl and share it here so we can help better.

Cheers!

bossotron13 (29)

@JustARatherRidi Thankyou, this explains it much better.

mat1 (2660)

You can do import file Then do file.variablename when you want to access a variable
Please mark my comment as the answer if it answered your question. Thanks!

bossotron13 (29)

@mat1 but when you import it just executes the whole code

mat1 (2660)

@bossotron13 Well, the variable won't be set if the code isn't run, so that's necessary. If you want parts of the code to not run while importing, put them in a function and call it later

bossotron13 (29)

@mat1 so yes but i imported it after the variables like so,
power = 3
import level2
and i try to print in level2 and it says not defined, any help?

mat1 (2660)

@bossotron13 In level2, add from main import power and then you can use the variable.