Python 3D Academyবাংলা

The global keyword (and why to avoid it)

🌍 In real life. Imagine any teacher could walk into the head office and change the school's timetable without telling anyone. It would work, until two teachers changed it at once, and nobody could tell who had changed what. A better school has one form: you ask for a change and get a new timetable back.

Python's global keyword is that unlocked office door.

The idea in one sentence: assigning to a name inside a function makes it local, unless you first write global name, which makes the function use the global name instead.

Its words:

  • global name: "in this function, name means the global one"
  • UnboundLocalError: the error when a function uses a local name before giving it a value
  • side effect: a change a function makes outside itself, like changing a global

Step by step, for count = count + 1 inside a function, without global:

  1. Before running the function, Python sees that it assigns to count, so count is local everywhere in it.
  2. To work out count + 1, Python looks for the local count.
  3. It has no value yet, so Python stops with an UnboundLocalError.
count = 0

def add_one():
    global count
    count = count + 1

add_one()
add_one()
print(count)

Without global, the same code stops with an UnboundLocalError: because the function assigns to count, Python treats count as local, and it has no value yet when count + 1 runs.

count = 0

def add_one():
    count = count + 1

add_one()

global works, but it makes code hard to follow: any function might secretly change any name. The cleaner way is to pass values in as arguments and send results out with return:

def add_one(count):
    return count + 1

count = 0
count = add_one(count)
count = add_one(count)
print(count)

Why avoid global? A function that takes its inputs as arguments and gives its result back with return can be understood by reading it alone, tested with any values, and called from anywhere. A function that quietly changes globals depends on, and changes, things you can't see in it, and bugs hide in exactly those places.

Mistakes and edge cases.

  • Using the name before global. print(count) above global count in the same function gives SyntaxError: name 'count' is used prior to global declaration. Put global first.
  • The UnboundLocalError. It appears even if the line that assigns comes after the line that reads: Python decides "local" for the whole function before running it.
  • global for lists. You don't need it to append to a global list; you only need it to reassign the name.
  • Forgetting to use the return value. add_one(count) alone throws the result away; write count = add_one(count).

Quiz

  1. What does this print?

    total = 5
    
    def reset():
        global total
        total = 0
    
    reset()
    print(total)
  2. What does this print?

    total = 5
    
    def reset():
        total = 0
    
    reset()
    print(total)
  3. Why is it usually better to return a new value than to use global?

    • You can see exactly what goes in and what comes out
    • global is slower
    • Functions can't read global names
  4. What does this print?

    def double(n):
        return n * 2
    
    n = 3
    n = double(n)
    n = double(n)
    print(n)
  5. Which line has a mistake?

    score = 0
    
    def win():
        score = score + 10
    
    win()

Coding tasks

  1. There's a global score = 0. Write add_point() that adds 1 to the global score, using global.

  2. Now the cleaner way: write add_points(score, n) that returns score + n, with no global at all.