ProgrammingBackend Developer

What is the variable scope in Python, and how does the `global` keyword work? Provide a practical example where misunderstanding scope leads to errors.

Pass interviews with Hintsage AI assistant

Answer.

The scope of a variable is the context in which it is accessible. In Python, there are 4 main scopes that can be remembered by the acronym LEGB:

  • Local — inside a function.
  • Enclosing — inside outer functions for nested functions.
  • Global — at the module level.
  • Built-in — Python's built-in names.

The global keyword allows modifying a variable declared at the global level from within a function.

def foo(): global my_var my_var = 10 # modifies the global variable

Without global, the variable is considered local inside the function, even if such a name exists in the outer scope.

Trick question.

"What will be the output of the following code?"

x = 10 def func(): x = 20 func() print(x)

Answer: It will print 10, because a new local variable x is created inside the function, the global one is not modified.

Examples of real errors due to misunderstandings of the topic.


Story

In a bot command handler, they wanted to keep a global counter but forgot about global:

counter = 0 def increment(): counter += 1 # UnboundLocalError: local variable 'counter' referenced before assignment

The error occurs because the interpreter thinks that counter is a local variable (since there is an assignment to it in the function), not global.


Story

In nested functions, they forgot that without the nonlocal keyword, a hidden variable creates a local scope:

def outer(): x = 0 def inner(): x += 1 # UnboundLocalError, x is considered local in inner

Correctly:

def outer(): x = 0 def inner(): nonlocal x x += 1

Story

They wrote a one-liner:

x = 5 y = (lambda: (x := x + 1))() # SyntaxError in Python < 3.8, or UnboundLocalError later

They forgot the difference in scope for expressions and lambda. Not all constructs support assignment inside lambda, depending on the version of Python.