How To Write Into A Single Variable From Different Modules In Python
1 min readNov 27, 2021
The aim of this pageđź“ť is to describe cross-module variable sharing. In the course of the runtime, I need to build an output
variable that I print for the user at the very and of a larger script that I decomposed into multiple modules.
1. notes
- I guess this would be discouraged by gurus, but still…
- context: all is happening within a single folder — no packages at play here
- manually, create a file dedicated to holding a cross-module variable, e.g.
config.py
- within the
config.py
, declare the variable that you will refer to from various modules, e.g.output={}
- in modules, where you need to write into the cross-module variable, import config module with
import config
at the top of the file - then, write into the cross-module variable with
<module>.<variable> = <value>
, e.g.
config.output["current_change"] = "./cu_output.csv"
- read/access the contents from cross-module variable from a different module with the same
<module>.<variable>
syntax, e.g.
for (k, v) in config.output.items():
print(k, "~~>", v)