3

I'm writing a Python program in which the main script initializes several variables with common data from the command line, config file, etc. I want the rest of the program to be able to access them as globals:

def abc() :
    global xyz
    _someOptionValue = xyz['someOptionName']
    ...

It doesn't work. I think that is because the global is defined in main.py (for example) and the function that references it is defined in abc.py (for example). Consequently the function's global namespace is different from the main script's namespace.

I think I should be able to get at the global variable by qualifying its name with the name of the main script's namespace, but what is that namespace's name?

Context: I currently pass these variables as parameters, and I know that many programmers consider that a cleaner solution. In this case I do not because the variables are set once, then are read throughout the whole program. In my judgement this is the strongest possible case (and the only justified case) for using global variables. If you think I shouldn't do it, I respect your opinion, but I don't share it; please respect mine!

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Jonathan Sachs
  • 613
  • 8
  • 19

1 Answers1

2

Create a globals module that contains all the shared information, and have every module (including main) import that module.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Thank you, this is the clearest answer. I was able to deduce the same thing from one of the answers in stackoverflow.com/q/142545/3001761?, but required some filling in. – Jonathan Sachs Apr 22 '15 at 19:14