Views:
483,624β
Votes: 2β
Tags:
python
share
global
Link:
π See Original Answer on Stack Overflow β§ π
URL:
https://stackoverflow.com/q/68278598
Title:
Using global variables between files?
ID:
/2021/07/07/Using-global-variables-between-files_
Created:
July 7, 2021
Upload:
September 15, 2024
Layout: post
TOC:
false
Navigation: false
Copy to clipboard: false
Based on above answers and links within I created a new module called global_variables.py
:
#!/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.