How To Share A Global Variable Across Files And Modules In Python

The aim of this page📝 is to share how I make certain variables accessible for different modules/files in Python.

Pavol Kutaj
1 min readJul 17, 2022
  • I do this not to repeat myself (DRY principle)
  • I am not using global keyword (no help here)
  • I am simplifying the approach from stack overflow
  • My use is in my short Jirc (Jira Card from Terminal) script
  • My global variable is a path to a config file that I need on various occasions in various places

1. STEPS

  • Move all globals to a file, I call this file settings.py
  • As we know, the code (outside of functions) is executed upon import statement
  • This fact binds a variable upon import to the proper environment frame and voila you have access to the variable
  • This is simply how my settings.py looks like
# settings.py
config_file_path = "./jirc/jirc/config.json"
  • Then, every other file that wants to share variables needs to import settings
  • My preference is to use from settings import * form that removes the need to use the module prefix
  • You could use import settings and refer to the global variable with settings.variable_name to make it more explicit
  • After import, variables are readily available

2. LINKS

--

--

No responses yet