Using global variables between files? Using global variables between files? python python

Using global variables between files?


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.pydef init():    global myList    myList = []

Next, your subfile can import globals:

# subfile.pyimport settingsdef stuff():    settings.myList.append('hey')

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

# main.pyimport settingsimport subfilesettings.init()          # Call only oncesubfile.stuff()         # Do stuff with global varprint settings.myList[0] # Check the result

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


See Python's document on sharing global variables across modules:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

config.py:

x = 0   # Default value of the 'x' configuration setting

Import the config module in all modules of your application; the module then becomes available as a global name.

main.py:

import configprint (config.x)

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.


You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.

A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.

So, in your example:

# ../myproject/main.py# Define global myList# global myList  - there is no "global" declaration at module level. Just inside# function and methodsmyList = []# Importsimport subfile# Do somethingsubfile.stuff()print(myList[0])

And:

# ../myproject/subfile.py# Save "hey" into myListdef stuff():     # You have to make the module main available for the      # code here.     # Placing the import inside the function body will     # usually avoid import cycles -      # unless you happen to call this function from      # either main or subfile's body (i.e. not from inside a function or method)     import main     main.mylist.append("hey")


matomo