Skip to content
Sign upLog in
← Back to Community

Importing

Profile icon
jerrygao1

How do you import a variable, such as level, from your main.py to a sub? I tried doing from main import level, but it didn't work.

Voters
Profile icon
Unknown12321
Profile icon
soryong72
Profile icon
jerrygao1
Comments
hotnewtop
Profile icon
[deleted]

Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

settings.py def init(): global myList myList = []

Next, your subfile can import globals:

subfile.py import settings def stuff(): settings.myList.append('hey')

Note that subfile does not call "init()"— that task belongs to "main.py":

main.py import settings import subfile settings.init() # Call only once subfile.stuff() # Do stuff with global var print settings.myList[0] # Check the result

This way, you achieve your objective while avoid initializing global variables more than once.