Python Forum
Clarity on global variables - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Clarity on global variables (/thread-38794.html)



Clarity on global variables - JonWayn - Nov-25-2022

I have some code in which I have global variables which are accessed within functions but only in some cases they are recognized. I read online that this can be overcome by adding the line global <var> at the top of the functions that access the variable, but why is it that other variables declared globally are recognized by the same function? Does the type of the variable matter - in the case I am dealing with the variable that is not recognized is an integer while the recognized ones are strings.

Thanks for any help


RE: Clarity on global variables - DeaD_EyE - Nov-25-2022

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-rule/#python-scope-vs-namespace
It explains the different namespaces and some Python internals.


RE: Clarity on global variables - JonWayn - Nov-26-2022

Thank you very much for that clear and thorough explanation