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.

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
Global Variable file
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. More on reddit.com
🌐 r/learnpython
4
13
June 13, 2021
passing global variables to another file in Python? - Stack Overflow
I have # file1.py global a, b, c, d, e, f, g def useful1(): # a lot of things that uses a, b, c, d, e, f, g def useful2(): useful1() # a lot of things that uses a, b, c, d, e, f, g def 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
🌐
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.
🌐
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 - My preference is to use from settings import * form that removes the need to use the module prefix · You could use import settings and refer to the global variable with settings.variable_name to make it more explicit · After import, variables are readily available · https://stackoverflow.com/questions/13034496/using-global-variables-between-files · Python ·
🌐
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.
🌐
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 ...
🌐
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 - To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
[SOLVED] use function variable from another file - Raspberry Pi Forums
It's only needed when you want to write to a global variable from within a function. To illustrate run this code: ... def test_1(): a = 666 def test_2(): global a a = 13 def test_() print(a) a=0 print(a) test_1() print(a) test_2() print(a) test_3() if you put that into a file called mymodule.py then import it into another python script you access a as mymodule.a
🌐
Reddit
reddit.com › r/learnpython › global variable file
r/learnpython on Reddit: Global Variable file
June 13, 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
🌐
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 .
🌐
W3Schools
w3schools.com › python › python_variables_global.asp
Python - Global Variables
If you use the global keyword, the variable belongs to the global scope: def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) Try it Yourself »
🌐
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 ...
🌐
Net Informations
net-informations.com › python › iq › global.htm
Global and Local Variables in Python - Net-Informations.Com
The global keyword in Python is used to indicate that a variable is a global variable, rather than a local variable. It allows you to access and modify the value of a global variable from within a function.
🌐
The Web Dev
thewebdev.info › home › how to use global variables between files in python?
How to use global variables between files in Python? - The Web Dev
October 19, 2021 - To use global variables between files in Python, we can use the global keyword to define a global variable in a module file. Then we can import the module in another module and reference the global variable directly.
🌐
Reddit
reddit.com › r/learnpython › global variable across files in a project
r/learnpython on Reddit: Global variable across files in a project
February 2, 2022 -

config/global_var.py has 10-20 variables which are used by ***main_methods/***main.py

Currently i see two options

  1. from config/global_var import *

  • not advisable generally

  • even if variable x is used in main, however user won't know where this variable is defined by IDE

  1. from config/global_var import x,y,z....

  • explicitly define all variables to be imported

  • takes too many lines if vars more than 20 30 etc

How do you import global variables in a project in a clean way while preserving reference to original file where it was defined?

Top answer
1 of 2
12

All that from config import ADDRESS, change_address does is take ADDRESS and change_address from your config module's namespace and dumps it into your current module's namespace. Now, if you reassign the value of ADDRESS in config's namespace, it won't be seen by the current module - that's how namespaces work. It is like doing the following:

>>> some_namespace = {'a':1}
>>> globals().update(some_namespace)
>>> a
1
>>> some_namespace
{'a': 1}
>>> some_namespace['a'] = 99
>>> a
1
>>> some_namespace
{'a': 99}

The simplest solution? Don't clobber name-spaces:

import config
config.change_address("192.168.10.100")
print("new address " + config.ADDRESS)
2 of 2
0

I would recommend that you try not to change the global state in a module. Instead, I would re-write the code such that ADDRESS in config.py doesn't change. If the configuration for your application can change from invocation to invocation I would change config to be something like:

ADDRESS = '0.0.0.0'

def get_default_config():
    return {'address': ADDRESS, 'some_other_config_value': 'foo'}

Then in main I would do:

app_config = config.get_default_config()
app_config = "192.168.10.100"
print("new address " + app_config['address']

As a general rule it isn't a good idea to change the value of variables/constants in other modules.

NOTE: You could also create a config class as well, so that you could access configuration values like config.address.

I recommend that you read the stackexchange post Why is Global State so Evil?