-1

How, in Python, do we create global variable that behave like in C/C++?

I mean, I'm in a team that shares most part of our code base with others teams. Each team has it own main file and function. And, some (lots) parts of the code have to behave in a slightly different way depending on the team that runs it.

How can I set a variable in the different mains, and then get it's value in every other files?

Here is what I tried, but in the end, team is always None in every files and functions/methods. I also tried all combination of adding global before accessing the variable team, the result is still the same.

# common.py
team = None
# main_a.py

from common import team

def main():
    ...
    team = "A"
    ...
    func()
# main_b.py

from common import team

def main():
    ...
    team = "B"
    ...
    func()
#  random_file.py

from common import team

def func():
    ...
    var = 3 if team == "A" else 5
    ...

I know there is a solution like 1 and 2, but it does not fit my needs, as the "global" variable is modified in the child function, and then read in the parent one, which is the opposite of what I'm trying to achieve.

Phantom
  • 833
  • 1
  • 9
  • 26
  • 1
    I think it will be better to use an environment variable in your use case instead of a common file for storing the value. It can be modified from any file/function and will reflect the modified value when you fetch it in any other file. – kush Aug 24 '23 at 12:43
  • 1
    Instead of `team=None` use `team={'name':None}` and update value of `name` as needed in different modules. – shaik moeed Aug 24 '23 at 12:43
  • The example from the [Python docs](https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules) that you posted is the simplest way to do it. But mutable shared global values are generally a bad idea and you should try and avoid it. In the example code it looks like it would be better design if `func` took `team` as an argument instead of using the global var. – Anentropic Aug 24 '23 at 12:49
  • you need `global team` in main() first before you use the variable. careful with race conditions if you're also multithreading. – Bobdabear Aug 24 '23 at 13:05

0 Answers0