Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Clarity on global variables
#1
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
Reply
#2
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.
Larz60+ and JonWayn like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thank you very much for that clear and thorough explanation
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Global variables or local accessible caslor 4 219 Jan-27-2023, 05:32 PM
Last Post: caslor
  global variables HeinKurz 3 372 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  I need some clarity on the use of the open command JonWayn 11 731 Nov-08-2022, 11:46 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 3,172 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 1,826 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 2,846 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  Question regarding local and global variables donmerch 12 3,587 Apr-12-2020, 03:58 PM
Last Post: TomToad
  local/global variables in functions abccba 6 2,308 Apr-08-2020, 06:01 PM
Last Post: jefsummers
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 2,021 Feb-09-2020, 02:05 PM
Last Post: new_to_python
  Please help me understand how to use global variables joew 6 2,526 Jan-05-2020, 06:03 PM
Last Post: joew

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020