3

I was wondering what the best way is to use global variables in a multi-script python project. I've seen this question: Using global variables between files? - and while the accepted answer works, the solution seems clunky.

See the below set of scripts. Only main.py is ever called directly; the rest are imported.

First, I've declared my global variables in a separate file:

#global_vars.py
my_string = "hello world"

The main.py prints the value of the string using a custom function, changes the value of the global variable, and then prints the new value

#main.py
import global_vars
import do_things_module

#Print the instantiated value of the global string
do_things_module.my_function()

#Change the global variable globally
global_vars.my_string = "goodbye"

#Print the new value of the global string
do_things_module.my_function()

do_things_module.py contains our custom print function, and gets the string straight from the global

#do_things_module.py
import global_vars

def my_function():
    print(global_vars.my_string)

Having to keep referencing global_vars.my_string rather than just my_string to ensure I'm always reading/writing to the global scoped variable seems long-winded and not very 'pythonic'. Is there a better/neater way?

Community
  • 1
  • 1
GIS-Jonathan
  • 3,167
  • 6
  • 28
  • 42

3 Answers3

0

If your goal is to use my_string instead of global_vars.my_string, you could import the module like this:

from global_vars import *

You should be able to use my_string directly.

ODiogoSilva
  • 2,314
  • 1
  • 16
  • 20
0

I would go with

import global_vars as g

Then you can refer to my_string from global_vars module as g.my_string in your code.

It doesn't use a lot of space, but it is still clear, that my_string came from global_vars and namespace isn't polluted

If you need only a few global_vars variables in your current module you can import only them

from global_vars import my_string, my_int

and reference to them as my_string and my_int

Alik
  • 19,655
  • 4
  • 44
  • 62
0

Best of all ("explicit is better than implicit") use

from module import name [as name] ...

but don't then expect to be able to modify the values seen by other modules (though you can mutate mutable objects, should you choose).

holdenweb
  • 24,217
  • 7
  • 45
  • 67