Variable from other files
bossotron13 (67)

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.

You are viewing a single comment. View All
JustARatherRidi (203)

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

If you write the following into and save it:

power = 9001

Then in, 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 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 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.


bossotron13 (67)

@JustARatherRidi Thankyou, this explains it much better.