Best way to share global variables between files in Python
Question: 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
in Python?](http://stackoverflow.com/questions/13034496/using-global-
variables-between-files-in-python) \- 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?


Answer: 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`

