Here is what is going on.

First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)

All you have to do to make a module-global variable is just assign to a name.

Imagine a file called foo.py, containing this single line:

X = 1

Now imagine you import it.

import foo
print(foo.X)  # prints 1

However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global declaration in your function, before you try to use the global.

def initDB(name):
    global __DBNAME__  # add this line!
    if __DBNAME__ is None: # see notes below; explicit test for None
        __DBNAME__ = name
    else:
        raise RuntimeError("Database name has already been set.")

By the way, for this example, the simple if not __DBNAME__ test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename; in that case, you should explicitly test for None using the is operator. I modified the example to add an explicit None test. The explicit test for None is never wrong, so I default to using it.

Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an from mymodule import *, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule and then say dir(mymodule) you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__ Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.

It is considered best practice in Python not to do import *, but to minimize the coupling and maximize explicitness by either using mymodule.something or by explicitly doing an import like from mymodule import something.

EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.

In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.

You can use a list but your code will be ugly:

__DBNAME__ = [None] # use length-1 list as a mutable

# later, in code:  
if __DBNAME__[0] is None:
    __DBNAME__[0] = name

A dict is better. But the most convenient is a class instance, and you can just use a trivial class:

class Box:
    pass

__m = Box()  # m will contain all module-level values
__m.dbname = None  # database name global in module

# later, in code:
if __m.dbname is None:
    __m.dbname = name

(You don't really need to capitalize the database name variable.)

I like the syntactic sugar of just using __m.dbname rather than __m["DBNAME"]; it seems the most convenient solution in my opinion. But the dict solution works fine also.

With a dict you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box in the above.

Answer from steveha on Stack Overflow
Top answer
1 of 5
334

Here is what is going on.

First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)

All you have to do to make a module-global variable is just assign to a name.

Imagine a file called foo.py, containing this single line:

X = 1

Now imagine you import it.

import foo
print(foo.X)  # prints 1

However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's default is to assume that function variables are local. You simply add a global declaration in your function, before you try to use the global.

def initDB(name):
    global __DBNAME__  # add this line!
    if __DBNAME__ is None: # see notes below; explicit test for None
        __DBNAME__ = name
    else:
        raise RuntimeError("Database name has already been set.")

By the way, for this example, the simple if not __DBNAME__ test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you can't just say if not variablename; in that case, you should explicitly test for None using the is operator. I modified the example to add an explicit None test. The explicit test for None is never wrong, so I default to using it.

Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be "private" to the module. If you ever do an from mymodule import *, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule and then say dir(mymodule) you will see the "private" variables in the list, and if you explicitly refer to mymodule.__DBNAME__ Python won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't want them rebinding that name to some value of their own.

It is considered best practice in Python not to do import *, but to minimize the coupling and maximize explicitness by either using mymodule.something or by explicitly doing an import like from mymodule import something.

EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesn't have the global keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.

In your functions, the global variable name will be read-only; you won't be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.

You can use a list but your code will be ugly:

__DBNAME__ = [None] # use length-1 list as a mutable

# later, in code:  
if __DBNAME__[0] is None:
    __DBNAME__[0] = name

A dict is better. But the most convenient is a class instance, and you can just use a trivial class:

class Box:
    pass

__m = Box()  # m will contain all module-level values
__m.dbname = None  # database name global in module

# later, in code:
if __m.dbname is None:
    __m.dbname = name

(You don't really need to capitalize the database name variable.)

I like the syntactic sugar of just using __m.dbname rather than __m["DBNAME"]; it seems the most convenient solution in my opinion. But the dict solution works fine also.

With a dict you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box in the above.

2 of 5
136

Explicit access to module level variables by accessing them explicity on the module


In short: The technique described here is the same as in steveha's answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).

Think of it like self for the current module instead of the current instance !

# db.py
import sys

# this is a pointer to the module object instance itself.
this = sys.modules[__name__]

# we can explicitly make assignments on it 
this.db_name = None

def initialize_db(name):
    if (this.db_name is None):
        # also in local function scope. no scope specifier like global is needed
        this.db_name = name
        # also the name remains free for local use
        db_name = "Locally scoped db_name variable. Doesn't do anything here."
    else:
        msg = "Database is already initialized to {0}."
        raise RuntimeError(msg.format(this.db_name))

As modules are cached and therefore import only once, you can import db.py as often on as many clients as you want, manipulating the same, universal state:

# client_a.py
import db

db.initialize_db('mongo')
# client_b.py
import db

if (db.db_name == 'mongo'):
    db.db_name = None  # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
# client_c.py
from db import db_name
# be careful when importing like this, as a new reference "db_name" will
# be created in the module namespace of client_c, which points to the value 
# that "db.db_name" has at import time of "client_c".

if (db_name == 'mongo'):  # checking is fine if "db.db_name" doesn't change
    db_name = None  # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.

As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.

๐ŸŒ
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 test3: Modules test1 and test2 are imported, f is called, and a is printed.
Discussions

Why not use global variables?
They add unneeded complexity and doubt into your code. Imagine you have a variable at the start of your program called "really_important" now imagine your code is 50,000 lines long and somewhere in there you import another module that also has a "really_important" global. Imagine trying to figure out which one is which, when they're used, when they're being modified, by whom, etc. Scope is a very powerful organizational tool. It helps you (and your IDE) remember what is important for any piece of code. For example: x = 0 y = 0 def add_x_y(): return x + y In the above you need to remember that this adds x and y together and inside the function you have zero assurance that x and y are even set. Contrasted with: def add_x_y(x, y): return x + y Not only is this shorter, the function prototype tells you exactly what you need to give it (two things named x and y), your IDE will helpfully provide you with insight about it, and the error you receive if you failed to define x or y properly will make a lot more sense. More on reddit.com
๐ŸŒ r/learnpython
31
21
July 27, 2021
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
python - Visibility of global variables in imported modules - Stack Overflow
I've run into a bit of a wall importing modules in a Python script. I'll do my best to describe the error, why I run into it, and why I'm tying this particular approach to solve my problem (which I... More on stackoverflow.com
๐ŸŒ stackoverflow.com
When declaring a global variable, do you "need" to make a function using it?
Your teacher needs to specify their question better, this is exactly how you declare a global variable. A better question might have been show how to use a declare global variable in a function. Source: Software developer (as my job) since 2000, switched to Python in 2008. EDIT: I re-read and notice your teacher is using w3schools to teach the lessons from, that's pretty shocking. People are pretty snobby about it, but I'd say it's OK for a quick reference but that's about all - it is absolutely not a good enough reference to be building a curriculum around. In the short term, just keep the guy somewhat happy, his attitude doesn't seem the most professional, just by using proper references (start with the actual python documentation, If you ever find yourself having to teach a python class in the future, then I would recommend actual books as reference; e.g. the O'Reilly book - Learning Python. At the point when I started developing everything was book based, and we had shelves of books in offices we worked in too, there were always O'Reilly books there (if you can, I'd recommend getting a book like that yourself). More on reddit.com
๐ŸŒ r/learnpython
60
10
July 31, 2024
๐ŸŒ
Real Python
realpython.com โ€บ python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions โ€“ Real Python
December 8, 2024 - The global scope, which exists at the module level ยท The built-in scope, which is a special scope for Pythonโ€™s built-in names ยท To illustrate, say that youโ€™re inside an inner function. In that case, Python can look for names in all four scopes. When you access a variable in that inner function, Python first looks inside that function.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_variables_global.asp
Python - Global Variables
Built-in Modules Random Module ... Interview Q&A Python Bootcamp Python Certificate Python Training ... Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ why not use global variables?
r/learnpython on Reddit: Why not use global variables?
July 27, 2021 -

I have people telling me to avoid using global variables in my functions. But why should I?

Top answer
1 of 14
40
They add unneeded complexity and doubt into your code. Imagine you have a variable at the start of your program called "really_important" now imagine your code is 50,000 lines long and somewhere in there you import another module that also has a "really_important" global. Imagine trying to figure out which one is which, when they're used, when they're being modified, by whom, etc. Scope is a very powerful organizational tool. It helps you (and your IDE) remember what is important for any piece of code. For example: x = 0 y = 0 def add_x_y(): return x + y In the above you need to remember that this adds x and y together and inside the function you have zero assurance that x and y are even set. Contrasted with: def add_x_y(x, y): return x + y Not only is this shorter, the function prototype tells you exactly what you need to give it (two things named x and y), your IDE will helpfully provide you with insight about it, and the error you receive if you failed to define x or y properly will make a lot more sense.
2 of 14
12
Global variables are not universially bad. It is absolutely fine to use global variables for constants, values that are not changed during the execution of the program. The thing that people (rightfully) warn about is writing to or modifying the values of global variables from functions as a means of sharing state between them or writing to global variables read by functions as means of passing data to them. Ideally, a function should be self-contained: it interacts with its environment only via the arguments it was passed and the value it returns. That has two distinct advantages: The function (and the program as a whole) is less prone to errors, since each function's behaviour is determined only by the code within it and the well-defined interface it has to other code via the calling mechanism. For example, if you have multiple active calls of the same function or set of functions, either due to multithreading or recursion, functions that share state globally can easily result in unwanted, hard-to-debug behaviour. It makes the function more reusable, since it is not entangled with the state of other unrelated functions or application-specific code. Say, you realise later in your project that you need to solve a problem you have already written a function for someplace else. It is that much easier just to directly reuse the existing function if you do not have to worry about the other code that surrounds it. That said, there are legitimate uses even for non-constant global variables. The issue is that those uses are highly specific/advanced. The things that beginner or intermediate programmers tend to use global variables for are not such legitimate uses, hence the oft repeated mantra of "global variables bad" you see in this sub.
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.

๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
February 27, 2025 - The singleton pattern ensures all modules share the same global state. Avoid modifying imported modules directly. Instead, use setter functions or classes. Use a dedicated config module for shared settings and constants. Consider using environment variables for sensitive or runtime-dependent settings.
Find elsewhere
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ faq โ€บ programming.html
Programming FAQ โ€” Python 3.14.3 documentation
Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.
๐ŸŒ
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 in one module, you can access 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 ...
๐ŸŒ
Net Informations
net-informations.com โ€บ python โ€บ iq โ€บ global.htm
Global and Local Variables in Python - Net-Informations.Com
Within the my_function function, ... global variable x outside of the function, it is still 10. The global keyword in Python is used to indicate that a variable is a global variable, rather than a local variable....
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python global variables
Python Global Variable โ€“ PYnative
October 21, 2022 - # global variable name = 'Jessa' ... function:', name)Code language: Python (python) Run ... We can use global variables across multiple functions of the same module....
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-define-global-variables-in-python-modules-398175
How to define global variables in Python modules | LabEx
In Python, global variables can be defined at the module level, which allows them to be accessed by multiple functions or classes within the same module.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-manage-module-global-variables-435508
How to manage module global variables | LabEx
Global variables are variables defined outside of any function or class, accessible throughout the entire module. They provide a way to share data across different parts of a Python script.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ global-keyword
Python Global Keyword (With Examples)
In Python, the global keyword allows us to modify the variable outside of the current scope.
๐ŸŒ
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 a module, not across all modules. (Unlike C, where a global is the same across all implementation files unless you explicitly 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 ...
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 โ€บ when declaring a global variable, do you "need" to make a function using it?
r/learnpython on Reddit: When declaring a global variable, do you "need" to make a function using it?
July 31, 2024 -

Recently, my teacher and I had some problems about this particular lesson that could not be solve because of both of us being stubborn. Note that this is a beginner class for programmers and the teacher was using a website w3schools to teach in his lesson. When he was revising the lesson in Python Variables, he asked "Create a global variable". Many students rose their hand then he decided to choose me. I went up to the board and wrote var1 = "hello, world!". You might say this is a very simple and easy line of code. I was sure this couldn't be wrong since I knew the definition global variable and that is variables that are created outside of a function (as in all of the examples in the previous pages in w3schools) are known as global variables. This definition tought me that I didn't need to make a function (like local variables) to make a global variable. Then afterwards he decided to mock me saying after I was wrong. Different from everyone else. I was wrong that my code needed more line. Specificly a function and an output to consider it as a global variable. This situation escalated to threatening me to the principle and calling about another teacher to prove me wrong. Ofcourse I did respond to this matter back respectfully but he couldn't agree with me. I was trying act like I was not mad to be respectful and not use any informal behaviour. Though I am starting to be annoyed of this. After all, he did told be to do my research to find "a professor" to proof me wrong, etc. I decided to ask reddit if I am truly in the wrong or not and to see any other opinions of my fellow reddit users about this matter. And if I am right, this reddit might be use to prove the teacher to getting my "deserving points" back from a complex misunderstanding.

Edit: var1 = "hello, world!" is written completely by itself and not inside of anything. And the teacher specificly said "Create a global variable" so that mean no function was mention. I hope this could give out some more ideas about the perspective. And as mention the class have only learnt to python variables so as of reading the comments, I couldn't even understand what some of the lines of code you guys wrote.

Top answer
1 of 11
28
Your teacher needs to specify their question better, this is exactly how you declare a global variable. A better question might have been show how to use a declare global variable in a function. Source: Software developer (as my job) since 2000, switched to Python in 2008. EDIT: I re-read and notice your teacher is using w3schools to teach the lessons from, that's pretty shocking. People are pretty snobby about it, but I'd say it's OK for a quick reference but that's about all - it is absolutely not a good enough reference to be building a curriculum around. In the short term, just keep the guy somewhat happy, his attitude doesn't seem the most professional, just by using proper references (start with the actual python documentation, If you ever find yourself having to teach a python class in the future, then I would recommend actual books as reference; e.g. the O'Reilly book - Learning Python. At the point when I started developing everything was book based, and we had shelves of books in offices we worked in too, there were always O'Reilly books there (if you can, I'd recommend getting a book like that yourself).
2 of 11
9
I think this is more of a weird interaction than a question about global variables. Teachers should not be "mocking" their students for getting a question wrong, regardless of whether the teacher is correct. But I'm only hearing your side of the story, so I won't make a judgement on that. That being said, this sounds like a problem that is not going to be solved by showing your teacher a reddit thread. So, with that out of the way, I'm going to disappoint you. The correct answer is...you're both right, but your teacher is more right. You are also somewhat both wrong, but I'll touch on that in a minute. There is nothing "special" about the scope of a module; it works just like a function scope. For example: def func1(): global_var = "hello" def func2(): print(global_var) func2() func1() # print(global_var) # Not defined error if uncommented # Output # hello Is global_var global? No, if you tried to print it outside func1 the code fails. All you've done is define a variable in a more "outer" scope compared to other functions. Still, for practical purposes, this is similar to a global variable. But it isn't actually global. For example: var1 = "hello, world!" def my_func(): var1 = "bye!" my_func() print(var1) # Output # hello, world! As you can see, your function doesn't actually modify the variable. Instead, a new local variable is created, assigned a value, and then promptly ignored. So this variable isn't "global" in the normal sense of the word. Instead, you would need to tell Python that you want to use the outer variable: var1 = "hello, world!" def my_func(): global var1 var1 = "bye!" my_func() print(var1) # Output # bye! The reality is that Python does not have "true" global variables. Any time a function needs to actually modify an outer variable, it must be declared as global within that scope. Read-only access is fine (which is why the print commands worked in the first example) because there is no confusion about whether or not you want to read an existing variable or create a new one. But any time you assign a value to a "global" variable you must tell the interpreter that this is your intent. Languages with "true" global variables don't require this because you define it as accessible everywhere at definition. In summary: You are correct that a variable defined at an outer scope can be read at an inner scope, similar to global variables. Your teacher is correct that without a global keyword definition, the variable is not actually global in the Pythonic sense. You are both wrong because true "global variables" are not a concept in Python. Using global variables is an antipattern anyway and you are both being immature for making it into a fight. In my opinion, number 4 is the most important. You hardly ever use the global keyword in actual programs and using variables in lower scopes is a "code smell". Don't be lazy...pass your parameters, and if you don't want to do that because the parameter is used a lot, create a class. You will almost never see this keyword in production code and having this go to the principle about something that is almost completely irrelevant to learning programming is bad behavior on both your parts, at least in my opinion. That probably isn't the answer you wanted. But it's the truth.
๐ŸŒ
Iram
iram.fr โ€บ IRAMFR โ€บ GILDAS โ€บ doc โ€บ html โ€บ gildas-python-html โ€บ node10.html
Global/local variables and module name spaces
When a variable is called in a function, Python searches it in the local name space and if not found, it searches it in the global name space. When a module is imported, it has its own global and locals name spaces, which it does not share with the main ones.