🔍 See Original Answer on Stack Overflow ⧉ 🔗
Using global variables between files?
July 7, 2021
December 3, 2023
Copy to clipboard: false
/assets/js/search.js will update text..
Based on above answers and links within I created a new module called
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================== # # global_variables.py - Global variables shared by all modules. # # ============================================================================== USER = None # User ID, Name, GUID varies by platform def init(): """ This should only be called once by the main module Child modules will inherit values. For example if they contain import global_variables as g Later on they can reference 'g.USER' to get the user ID. """ global USER import getpass USER = getpass.getuser() # End of global_variables.py
Then in my main module I use this:
import global_variables as g g.init()
In another child imported module I can use:
import global_variables as g # hundreds of lines later.... print(g.USER)
I’ve only spent a few minutes testing in two different python multiple-module programs but so far it’s working perfectly.