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.

Answer from Alex Martelli on Stack Overflow
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.

🌐
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.
Discussions

Global variables shared across modules
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 ... More on discuss.python.org
🌐 discuss.python.org
0
0
June 25, 2022
python - Using global variables between files? - Stack Overflow
DON'T DO import *. Your global variables will no longer remain in sync. Each module receives its own copy. Changing the variable in one file will not reflect in another. It is also warned against in docs.python.org/2/faq/… 2016-02-07T14:11:06.49Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
How to import variable from another file if another file write the code inside def main():
The whole purpose of a function is to enclose local variables and not expose them to the outside. If you want a function to have some value from main, you pass that value as an argument when you call that function. def main(): v = 1 otherfunc(v) def otherfunc(v): #now otherfunc has access to v's value print(v) More on reddit.com
🌐 r/learnpython
11
0
March 26, 2022
I can't import global variable from another python file

global totalUp just means that the name lookup is global. You still need to make that variable. Usually you would see

global totalUp
totalUp = None # set to initial value

Note that the global keyword is redundant if you are not in a function.

More on reddit.com
🌐 r/learnpython
4
1
April 4, 2019
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
[SOLVED] use function variable from another file - Raspberry Pi Forums
Fri Apr 09, 2021 10:59 pm if i import the function from another file it doesn't, A variable from another module is "namespaced" to that module. "a" in first script and "a" in the second one are different variables! mod1.py ... import mod2 a = "mod1" def func1(): global a a = "mod1_func1" print(f"mod1 : {a}") func1() print(f"mod1 func1: {a}") mod2.func2() print(f"mod2 func2: {a}") print(f"mod2.a: {mod2.a}") mod2.py
🌐
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 ...
🌐
Quora
quora.com › How-do-I-share-global-variables-between-files-in-Python
How to share global variables between files in Python - Quora
Sharing global variables between Python files is done by placing those variables in a single module and importing that module wherever you need access. Use module-level variables, and mutate them explicitly when necessary.
🌐
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.
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.
🌐
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 .
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-import-variables-from-another-file-in-python
How to import variables from another file in Python? - GeeksforGeeks
April 3, 2025 - To import variables from another file in Python, you need to use the import statement. By importing a file, you gain access to its variables and functions. This can be done by simply using import filename or from filename import variable_name ...
🌐
Codingdeeply
codingdeeply.com › home › python global variables across files: how to share data between modules
Python Global Variables Across Files: How to Share Data Between Modules
February 23, 2024 - This is done by creating a Python module that contains the global variables and using the import statement to access them in a different module. ... In this example, we define a global variable x in file1.py and import it into file2.py using ...
🌐
Stack Overflow
stackoverflow.com › questions › 61552061 › use-global-variable-from-another-file-in-an-imported-class
python - Use global variable from another file in an imported class - Stack Overflow
If you genuinely need it in both modules, just import it. ... Absolutely there is a better way, don't rely on global mutable state. That is a well-known anti-pattern. Instead, explicitly pass arguments to functions, or alternatively, use a class to encapsulate state (in this case, with a class variable if you want it to be shared by all A objects) – juanpa.arrivillaga Commented May 2, 2020 at 1:28 ... You could create a file, like utils.py, and in it put LIST (or if you don't want to add an extra file, you could take on circular dependencies).
🌐
EyeHunts
tutorial.eyehunts.com › home › python import variable from another file | example code
Python import variable from another file | Example code
August 1, 2022 - First import the file from the current program, then you can import the variable or access the variable in Python. There are three approaches to importing variables from another file.
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 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.

🌐
Reddit
reddit.com › r/learnpython › global variable file
r/learnpython on Reddit: Global Variable file
May 4, 2021 -

So currently I am working on a project where I decided to make a file called global_variables.py. This file consists of python dictionaries where I would like to store data throughout the process of the program.

The program consists of 3 classes that are called one by one by a main.py file. Each class import the global variables files and makes changes to the file. Now I realized that this is not the way to go because each class makes a different iteration of the global variable files.

How can I approach this so the global variables gets "saved" ready for the next class to import it and use it? Should I just use a JSON file?

Top answer
1 of 3
8
Now I realized that this is not the way to go because each class makes a different iteration of the global variable files. No that's not true. When the second file imports something python does not reload the import, it simply makes an alias to the already imported one. Your plan will work. However it's a very odd way to do things. You are basically using a module (python file) as a mutable class instance ... Why don't you just use a class instance? It seems a dataclass is exactly what you need. Edit: for example: from dataclasses import dataclass @dataclass class GlobalData: breakfast:str = "spam" lunch:str = "spam" dinner:str = "spam" # load / save code goes here (if you want it). class Compute: def __init__(self, global_data): self.global_data = global_data def set_lunch(self, value): self.global_data.lunch = value class Display: def __init__(self, global_data): self.global_data = global_data def show(self): print(f"you are having {self.global_data.breakfast} for breakfast") print(f"you are having {self.global_data.lunch} for lunch") print(f"you are having {self.global_data.dinner} for dinner") def main(): # initialize your variable container data = GlobalData(breakfast="eggs") # pass the data to a class to use it c = Compute(data) c.set_lunch("BLT") # mutate the data d = Display(data) d.show() if __name__ == '__main__': main() If it helps your code organization each of those classes and / or the main function could be in separate files and imported.
2 of 3
2
If you want to have variables per class rather than variables per instance, you can declare class variables. class MyGlobalClass: one_per_class = 200 class_var = 0 # These are class variables def __init__(): self.instance_var = 0 # this is an instance variable