The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

# settings.py

def init():
    global myList
    myList = []

Next, your subfile can import globals:

# subfile.py

import settings

def stuff():
    settings.myList.append('hey')

Note that subfile does not call init()— that task belongs to main.py:

# main.py

import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result

This way, you achieve your objective while avoid initializing global variables more than once.

Answer from Hai Vu on Stack Overflow
🌐
Python.org
discuss.python.org › python help
Global variables shared across modules - Python Help - Discussions on Python.org
June 25, 2022 - Hello to all Pythonians here. I encountered a strange behavior about the global keyword and modules, which I cannot understand. Module test1: Variable a is created Module test2: Module test1 is imported, and function f is created, which modifies variable a through the global keyword Module ...
Discussions

python - How to make a cross-module variable? - Stack Overflow
If a programmer picks up your 'global' variable using 'from a import var', (try this variation in c.py) they obtain a copy of the variable at the time of import. 2015-07-28T23:36:01.467Z+00:00 ... @pevogam: no, import doesn't copy objects. I bet you've used from a import var (var is in different namespace now) instead of import a as in my answer. (var remains in the a module namespace). The object is the same, no copy in both cases. Related: In Python... More on stackoverflow.com
🌐 stackoverflow.com
How to share global variables between python files - Python Programming - Visual Components - The Simulation Community
I have one task list (tasks = [task1,task2,task3]) to be executed using AGV caller, however new task will be assigned using tasks.append(new task) as well when running the current task list. How can two scripts using the… More on forum.visualcomponents.com
🌐 forum.visualcomponents.com
0
December 14, 2018
Global Variable from a different file Python - Stack Overflow
By the way, as a general principle, it's not really recommended to do from module import * because it makes it hard to see where any given imported variable comes from. Also, don't end your statements with semicolons in Python. ... Importing file2 in file1.py makes the global (i.e., module ... More on stackoverflow.com
🌐 stackoverflow.com
python - Global variable with imports - Stack Overflow
Here is what you need to understand (copied from Matloff's book): Python does not truly allow global variables in the sense that C/C++ do. An imported Python module will not have direct access to the globals in the module which imports it, nor vice versa. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 10
367

Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)

There are different ways to solve this, depending on your actual use case.


Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it's just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

Don't use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.


Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:

import builtins
import module1
builtins.a = 3
module1.f()
2 of 10
18

As a workaround, you could consider setting environment variables in the outer layer, like this.

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

As an extra precaution, handle the case when MYVAL is not defined inside the module.

🌐
Visual Components
forum.visualcomponents.com › python programming
How to share global variables between python files - Python Programming - Visual Components - The Simulation Community
December 14, 2018 - I have one task list (tasks = [task1,task2,task3]) to be executed using AGV caller, however new task will be assigned using tasks.append(new task) as well when running the current task list. How can two scripts using the same global variable. I tested the import X.py module like below doesn’t work.
🌐
Net Informations
net-informations.com › python › iq › global.htm
Global and Local Variables in Python - Net-Informations.Com
How to share a global variable across python modules, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.
Find elsewhere
🌐
Instructobit
instructobit.com › tutorial › 108 › How-to-share-global-variables-between-files-in-Python
How to share global variables between files in Python
October 24, 2020 - import globals import test if __name__ == "__main__": globals.initialize() print( globals.num ) # print the initial value test.increment() print( globals.num ) # print the value after being modified within test.py ... As you can see, once we've initialized the global variable in globals.py, we can then access 'num' as a property from any other module within the application and it will retain its value.
Top answer
1 of 8
112

Importing file2 in file1.py makes the global (i.e., module level) names bound in file2 available to following code in file1 -- the only such name is SomeClass. It does not do the reverse: names defined in file1 are not made available to code in file2 when file1 imports file2. This would be the case even if you imported the right way (import file2, as @nate correctly recommends) rather than in the way you're doing it.

Apparently you want to make global names defined in file1 available to code in file2 and vice versa. This is known as a "cyclical dependency" and is generally not recommended.

It is often more useful to discuss ways to avoid cyclic dependencies.

For example, you could put global names that need to be available to both modules in a third module (e.g. file3.py, to continue your naming streak;-) and import that third module into each of the other two (import file3 in both file1 and file2, and then use file3.foo etc, that is, qualified names, for the purpose of accessing or setting those global names from either or both of the other modules, not barenames).

Of course, more and more specific help could be offered if you clarified (by editing your Q) exactly why you think you need a cyclical dependency. Note that it is usually not the right answer.

2 of 8
36

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in file1.py:

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

🌐
Index.dev
index.dev › blog › how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
February 27, 2025 - One way to use global variables across modules is to define them in a separate module and import them where needed.
Top answer
1 of 3
25

Try:

def changeGlobal():
    global myGlobal
    myGlobal = "bye"

Actually, that doesn't work either. When you import *, you create a new local module global myGlobal that is immune to the change you intend (as long as you're not mutating the variable, see below). You can use this instead:

import nice

nice.changeGlobal()
print nice.myGlobal

Or:

myGlobal = "hello"

def changeGlobal():
   global myGlobal
   myGlobal="bye"

changeGlobal()

However, if your global is a mutable container, you're now holding a reference to a mutable and are able to see changes done to it:

myGlobal = ["hello"]

def changeGlobal():
    myGlobal[0] = "bye"
2 of 3
8

I had once the same concern as yours and reading the following section from Norman Matloff's Quick and Painless Python Tutorial was really a good help. Here is what you need to understand (copied from Matloff's book):

Python does not truly allow global variables in the sense that C/C++ do. An imported Python module will not have direct access to the globals in the module which imports it, nor vice versa.

For instance, consider these two files, x.py,

# x.py
import y
def f():
  global x
  x = 6
def main():
  global x
  x = 3
f()
y.g()
if __name__ == ’__main__’:
  main()

and y.py:

# y.py
def g():
  global x
  x += 1

The variable x in x.py is visible throughout the module x.py, but not in y.py. In fact, execution of the line x += 1

in the latter will cause an error message to appear, “global name ’x’ is not defined.”

Indeed, a global variable in a module is merely an attribute (i.e. a member entity) of that module, similar to a class variable’s role within a class. When module B is imported by module A, B’s namespace is copied to A’s. If module B has a global variable X, then module A will create a variable of that name, whose initial value is whatever module B had for its variable of that name at the time of importing. But changes to X in one of the modules will NOT be reflected in the other.

Say X does change in B, but we want code in A to be able to get the latest value of X in B. We can do that by including a function, say named GetX() in B. Assuming that A imported everything from B, then A will get a function GetX() which is a copy of B’s function of that name, and whose sole purpose is to return the value of X. Unless B changes that function (which is possible, e.g. functions may be assigned), the functions in the two modules will always be the same, and thus A can use its function to get the value of X in B.

Top answer
1 of 5
172

You are using from bar import a. a becomes a symbol in the global scope of the importing module (or whatever scope the import statement occurs in).

When you assign a new value to a, you are just changing which value a points too, not the actual value. Try to import bar.py directly with import bar in __init__.py and conduct your experiment there by setting bar.a = 1. This way, you will actually be modifying bar.__dict__['a'] which is the 'real' value of a in this context.

It's a little convoluted with three layers but bar.a = 1 changes the value of a in the module called bar that is actually derived from __init__.py. It does not change the value of a that foobar sees because foobar lives in the actual file bar.py. You could set bar.bar.a if you wanted to change that.

This is one of the dangers of using the from foo import bar form of the import statement: it splits bar into two symbols, one visible globally from within foo which starts off pointing to the original value and a different symbol visible in the scope where the import statement is executed. Changing a where a symbol points doesn't change the value that it pointed too.

This sort of stuff is a killer when trying to reload a module from the interactive interpreter.

2 of 5
34

One source of difficulty with this question is that you have a program named bar/bar.py: import bar imports either bar/__init__.py or bar/bar.py, depending on where it is done, which makes it a little cumbersome to track which a is bar.a.

Here is how it works:

The key to understanding what happens is to realize that in your __init__.py,

from bar import a

in effect does something like

a = bar.a
# … where bar = bar/bar.py (as if bar were imported locally from __init__.py)

and defines a new variable (bar/__init__.py:a, if you wish). Thus, your from bar import a in __init__.py binds name bar/__init__.py:a to the original bar.py:a object (None). This is why you can do from bar import a as a2 in __init__.py: in this case, it is clear that you have both bar/bar.py:a and a distinct variable name bar/__init__.py:a2 (in your case, the names of the two variables just happen to both be a, but they still live in different namespaces: in __init__.py, they are bar.a and a).

Now, when you do

import bar

print bar.a

you are accessing variable bar/__init__.py:a (since import bar imports your bar/__init__.py). This is the variable you modify (to 1). You are not touching the contents of variable bar/bar.py:a. So when you subsequently do

bar.foobar()

you call bar/bar.py:foobar(), which accesses variable a from bar/bar.py, which is still None (when foobar() is defined, it binds variable names once and for all, so the a in bar.py is bar.py:a, not any other a variable defined in another module—as there might be many a variables in all the imported modules). Hence the last None output.

Conclusion: it is best to avoid any ambiguity in import bar, by not having any bar/bar.py module (since bar.__init__.py makes directory bar/ a package already, that you can also import with import bar).

🌐
TutorialsPoint
tutorialspoint.com › Explain-the-visibility-of-global-variables-in-imported-modules-in-Python
Explain the visibility of global variables in imported modules in Python?
October 1, 2019 - Globals in Python are global to ... make it static.). If you need truly global variables from imported modules, you can set those at an attribute of the module where you're importing it....
🌐
Medium
pavolkutaj.medium.com › how-to-share-a-global-variable-across-files-and-modules-in-python-e909358cf5a4
How To Share A Global Variable Across Files And Modules In Python | by Pavol Z. Kutaj | Medium
July 17, 2022 - You could use import settings and refer to the global variable with settings.variable_name to make it more explicit ... Support Engineer at ClickHouse. Notes from my AI-Assisted journeys of learning software and walks with ANKI cards, with learning and dictating my reflections.
🌐
Python
docs.python.org › 3 › faq › programming.html
Programming FAQ — Python 3.14.3 documentation
Guido van Rossum recommends avoiding all uses of from <module> import ..., and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › global variables in python
Global Variables in Python
August 15, 2024 - If you declare a global variable ... it in another module by importing it. It's important to note that if you try to modify a global variable without declaring it as global within a function or class method, Python will treat it as a new local ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › common mistakes when dealing with multiple python files
Common Mistakes When Dealing with Multiple Python Files | Towards Data Science
January 28, 2025 - I purposely made this example a bit complicated; here we have a gloabl_.py python file that contains num=10 . But in the main.py file, I created an num=5 as well. It can tell you the differences even though they were both named as num , but they are in a different scope. In the main.py , we modify this GLOBAL variable by adding 1, and the change will be reflected in sub_module.py as well. Noting here I have to import global_ within the test_func2 function because if I put the import syntax in the beginning, num it imported will be the one prior to the execution of lineglobal_.num += 1 .
🌐
Reddit
reddit.com › r/learnpython › global variable not changing across modules?
r/learnpython on Reddit: Global variable not changing across modules?
March 19, 2017 -

Hey, I'm a beginner making a game with a GSM (game state manager) which stores the current state in a global variable 'state.' Each state is represented by a module and the goal is being able to enter new states within a state module by modifying GSM's 'state.' However, I got stuck and made this SSCCE of it:

module loop:

import globalchanger
globalvar = -1
def main():
    global globalvar
    while True:
        if globalvar == 1337:
            print('globalvar change recognized in main')

def changeglobalvar():
    global globalvar
    globalvar = 1337
    print('globalvar changed to '+str(globalvar))

if __name__ == '__main__':
    main()

module globalchanger:

import loop
loop.changeglobalvar()

Running the loop module prints 'globalvar changed to 1337' and then loops indefinitely. AFAIK the main function should recognize the changed value of globalvar and print 'globalvar change recognized in main,' but it doesn't. This is the essence of my GSM issue outlined above.

Does anyone get this? Any help would be much appreciated and thanks in advance!

Top answer
1 of 2
4
To understand where this is going wrong, you need to read up on python imports and namespaces. It's a bit late, but to give you the TL;DR, a few things to keep in mind... Every module you import has its own global namespace. It doesn't all get loaded into your main namespace. This is an issue when you are importing loop, because at that point you're not loading the main app itself, you're now loading loop as a module with its own namespace. So what you're doing is the following flow: Starting App -> Starts in main namespace Importing globalchanger -> globalchanger imports loop (as a module, with its own global namespace) -> then run loop.changeglobalvar, which uses loop's global globvar, and changes that to 1337 then jumps back to the main app, which is checking for the global globalvar in it's own global namespace. In reality, the main app's global globalvar never changed. You changed the global globalvar in the loop module. You can see this by adding print(loop.globalvar) after you run the function in globalchanger. It will properly print out 1337, which the app will then happily proceed to ignore. Now, there are a few things you could do... but for the sake of not having you bang your head against this and keep trying to do fucked up circular imports (or fucking, import __main__), I'll just give a recommendation. Don't store your game state as a global variable. Honestly, don't store anything as a random global variable in your main app file if you can help it. Keep it in a separate file, which you can then import into all of your modules. The reason this works is because when you imported loop above, you imported loop, not__main__, so it wasn't treating the global vars defined within as actually being the same objects. But you don't want to do import __main__, because that's fucking stupid. If you keep all of it as a separate module, which you then import into __main__ AND into your other files, it WILL treat them as the same. Basically if you import a module into any number of other modules, it will treat that as the same across them all. So basically, just add a third file. loop.py import state import globalchanger def main(): while True: if state.globalvar == 1337: print('globalvar change recognized in main') def changeglobalvar(): state.globalvar = 1337 print('globalvar changed to '+str(state.globalvar)) if __name__ == '__main__': main() globalchanger.py import loop loop.changeglobalvar() state.py globalvar = -1 By doing this, you're always checking the actual game state's globalvar, and you're always editing the same variable. Also, if you did import state in another module (say, you wanted to offload some of your functions to the globalchanger module?), you could import state there and be 100% sure you are working with the same variables you're reading in your main loop.
2 of 2
1
Hi! I'm working on a bot to reply with suggestions for common python problems. This might not be very helpful to fix your underlying issue, but here's what I noticed about your submission: You appear to be using concatenation and the str function for building strings Instead of doing something like result = "Hello " + name + ". You are " + str(age) + " years old" You should use string formatting and do result = "Hello {}. You are {} years old".format(name, age) See the python tutorial for more information.
🌐
Quora
quora.com › How-do-I-share-global-variables-between-files-in-Python
How to share global variables between files in Python - Quora
Another reason why you might have difficulty with global variables, if you are coming from the world of C, is that global variables are ONLY defined within a module; you have to use a dot notation to make use of a variable from one module in another ...
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
global variables between modules - Raspberry Pi Forums
September 6, 2022 - # main.py from data import variables # code which should run only, if it is not an imported module if __name__ == "__main__": print("From main.py: start_time before import") print(f"From main.py: {variables.start_time}") import initialization print("From main.py: start_time after import") print(f"From main.py: {variables.start_time}") ... How global variables work, with "across modules" about half way down the page. https://www.programiz.com/python-progra ...