How do I share global variables across modules - python

+1 vote
How do I share global variables across modules in python?
Jul 24, 2019 in Python by Dipti
141,597 views

3 answers to this question.

+1 vote

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name.

config.py

x = 0

mod.py:

import config
config.x = 1

main.py:

import config
import mod
print(config.x)


Hope it works!!

If you are a beginner and need to know more about Python, It's recommended to go for Python Certification course today.

Thanks!

answered Jul 24, 2019 by Faiza
It's extremely helpful.
Thank you.
0 votes

Global variables can be used by everyone, both inside of functions and outside.

  1. Create a variable outside of a function, and use it inside the function. ...
  2. Create a variable inside a function, with the same name as the global variable. ...
  3. If you use the global keyword, the variable belongs to the global scope:

.Ready to unlock the power of data? Join our Data Science with Python Course and gain the skills to analyze, visualize, and make data-driven decisions.

answered Dec 15, 2020 by Gitika
• 65,730 points