The
global
is only required if you do an assignment.
Assign the int
42
to the name
a
a = 42
An assignment inside a function is in function scope and does not affect module scope.
a = 42
def foo():
a = 13
print(a)
foo() # prints 13
print(a) # prints 42
Now the same with global:
a = 42
def foo():
global a
# a is now assigned on module scope
a = 13
print(a)
foo() # prints 13
print(a) # prints 13
If you have mutable objects, then you don't need global.
my_list = [1, 2, 3]
def sideeffect():
# here is no assignment
# instead the mutable object is modified inline
my_list.append(10)
print(my_list) # [1, 2, 3]
sideeffect()
print(my_list) # [1, 2, 3, 10]
You can mutate mutable objects on module scope from a function without the use of global.
I named the function
sideeffect
because the function is causing a side effect.
my_list
is modified on module scope.
The best way to get rid of
global
are classes. A class holds state and has methods, which are doing something with the state. The instances of classes are isolated from each other.
class MyList:
"""
Usually a class has more than one method.
This is a very minimal example.
"""
def __init__(self, elements=None):
# self is the instance of the class and elements holds the list, which
# was created during instantiation (__init__)
self.elements = elements or [] # if elements is None, then [] is assigned to self.elements
def add(self):
self.elements.append(10)
l1 = MyList()
l2 = MyList()
l1.add()
l1.add()
l2.add()
print(l1.elements) # [10, 10]
print(l2.elements) # [10]
You should read this article:
https://realpython.com/python-scope-legb...-namespace
It explains the different namespaces and some Python internals.