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

Global variables shared across modules
Yes, that was a super explanation from Václav. 👍 I ran it just to have a look and put the example in my “training” library. It’s hard to tell who has coding experience and who is venturing into coding with Python, but… Luc, you may recognize this as an example of namespace. More on discuss.python.org
🌐 discuss.python.org
0
0
June 25, 2022
When should I use a global variable module in Python? - Software Engineering Stack Exchange
In Python projects, if your project spans multiple Python modules and you need to pass some data between the modules, as far as I know, there's 2 main ways: Pass the data as function arguments Cre... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
October 31, 2021
Dealing with global variables and multiple modules
Subreddit for posting questions ... learning python. ... Right now I'm writing some code that is separated into two modules. One of the modules contains class definitions (call it classes.py), and the other is the main program that imports these classes and uses them (main.py). The problem is, some of the classes in classes.py rely on global variables that are defined ... More on reddit.com
🌐 r/learnpython
12
2
January 19, 2016
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
🌐
Python Forum
python-forum.io › thread-11873.html
Sharing variables across modules
Hey all, today I somehow managed to get stuck with getting a variable in one module changed by a function in another module - something I had working last time I wrote multi-module scripts. Simplifying the code (otherwise requiring Kivy to run), I h...
🌐
Python.org
discuss.python.org › python help
Global variables shared across modules - #5 by mlgtechuser - 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 funct…
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-share-global-variables-across-modules-in-python
How do I share global variables across modules in Python?
September 19, 2022 - # Variable i = 10 # Function def ... print(i) ... Now, to share information across modules within a single program in Python, we need to create a config or cfg module....
🌐
Python documentation
docs.python.org › 3 › tutorial › modules.html
6. Modules — Python 3.14.3 documentation
Each module has its own private namespace, which is used as the global namespace by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables.
🌐
Python
docs.python.org › 3 › faq › programming.html
Programming FAQ — Python 3.14.3 documentation
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as ...
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_variables_global.asp
Python - Global Variables
Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function · x = "awesome" def myfunc(): print("Python is " + x) myfunc() Try it Yourself »
🌐
Great Learning
mygreatlearning.com › blog › it/software development › global variables in python
Global Variables in Python
August 15, 2024 - ● Access across modules: Global variables can be accessed across different modules within the same program. If you declare a global variable in one module, you can access it in another module by importing it.
Top answer
1 of 1
8

Once upon a time in the early days of computers, there were no function parameters or return values. There were only global variables. This was an utter mess and completely unmaintainable. It is really difficult to track how data flows through such a “spaghetti code” program that uses global variables to communicate, because every part of the code could change everything.

Python is a very flexible languages, so it is possible to reach into another module and change its global variables (especially since there are no true constants in Python). But with great power comes great responsibility. It is rarely appropriate to do this. Legitimate examples I have seen include:

  • monkey-patching for tests
  • initializing and configuring singletons
  • manipulating process-global data such as sys.env

In the comments, you mention django.conf.settings. Since these settings are by design process-global (you can only have one Django app running per process) it's OK to access and modify those settings. However, if I had designed Django, I might have chosen another approach for configuring settings that does not rely on global variables.

For software that you are designing, it is probably better to make your data flows explicit and to pass data via function parameters and return values. If you have a lot of related data, you can create a class to group these variables. With Python 3.7 dataclasses, it is now very easy to create such classes. I find that this helps to write well-structured and easy to test code: all the data dependencies are explicit, which helps to figure out what has to be provided in a test case. If a function depends on a lot of unrelated stuff, this could indicate that the code has been structured in an awkward way.

For example, consider this code where we have some business logic to transform data and save it in a database:

DB_CONNECTION = ...
DATA = ...

def my_function() -> None:
  # some tricky business logic
  DATA['y'] += DATA['x']**2
  DB_CONNECTION.execute('INSERT INTO table VALUES(?, ?)', (DATA['x'], DATA['y']))

# caller:
DB_CONNECTION = ...
DATA = ...
my_function()

A caller of this function must make sure that the DB_CONNECTION and DATA variables are initialized before calling the function. Such “temporal dependencies” are bad API design in most cases. Here, we have also introduced an artificial constraint that there can only be one connection and one data in the program.

We could refactor this by turning those variables into function arguments. This makes it clear to the caller what has to be provided for the function to work. It also makes it much more straightforward to test the function:

def my_function(data: Data, *, conn: Connection) -> None:
  # some tricky business logic
  data['y'] += data['x']**2
  conn.execute('INSERT INTO table VALUES(?, ?)', (data['x'], data['y']))

# caller:
my_function(..., conn=...)

But why is this function taking both data and a database connection? For testing the tricky business logic, we would still have to provide a database connection and then read the data back from the database. In some cases, this can be simplified by splitting this code into a “pure” part that just manipulates our data, and a part that performs external interaction.

def my_inplace_transformation(data: Data) -> None:
  # some tricky business logic
  data['y'] += data['x']**2

# pure alternative that does not modify data:
def my_transformation(data: Data) -> Data:
  return { 'y': data['x']**2, **data }

def save_data(data: Data, *, conn: Connection) -> None:
  conn.execute('INSERT INTO table VALUES(?, ?)', (data['x'], data['y']))

# caller:
data = ...
my_inplace_transformation(data)
# alternative: data = my_transformation(data)
save_data(data, conn=...)

Here, the caller has regained a bit of responsibility: it's now the caller's job to pass the data between the functions, in particular to call the save_data() function if the data shall be saved. But now the main business logic is nicely isolated and very easy to test.

🌐
Python
peps.python.org › pep-0008
PEP 8 – Style Guide for Python Code | peps.python.org
(Let’s hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions. Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are “module non-public”).
🌐
Quora
quora.com › How-will-you-share-variables-across-modules-in-Python
How will you share variables across modules in Python? - Quora
Answer: Experienced beginner here :-) You really want the actual variable to live in one obvious place, even if that is a module all of its own. Then as much as possible, consider passing it into functions etc as an argument, then the code inside doesn't get tied to the specific place you keep th...
🌐
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 - This fact binds a variable upon import to the proper environment frame and voila you have access to the variable ... You could use import settings and refer to the global variable with settings.variable_name to make it more explicit
🌐
Reddit
reddit.com › r/learnpython › dealing with global variables and multiple modules
r/learnpython on Reddit: Dealing with global variables and multiple modules
January 19, 2016 - You can always update the variables within the config module. The python FAQ actually has an example specifically for this: https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules
🌐
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 - Every command in this Python file ... the functions globally by declaring itglobal. ... However, global variables are not shared across different Python files....
🌐
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.
🌐
FastAPI
fastapi.tiangolo.com › tutorial › bigger-applications
Bigger Applications - Multiple Files - FastAPI
To learn more about Python Packages and Modules, read the official Python documentation about Modules. We are importing the submodule items directly, instead of importing just its variable router.
🌐
Index.dev
index.dev › blog › how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
February 27, 2025 - Global variables in Python let you store values that you can access across multiple modules in your project.
🌐
PYnative
pynative.com › home › python › python global variables
Python Global Variable – PYnative
October 21, 2022 - First, create a special module config.py and create global variables in it. Now, import the config module in all application modules, then the module becomes available for a global name.