Skip to main content

Python 'global' and 'nonlocal' Keywords Explained with Examples

In Python, the keywords global and nonlocal are used when dealing with variable scope. In other words, they help determine where a variable is located when you access or modify it.

1. Scope Refresher

Before we jump in, remember that scope refers to the part of a program where a variable is accessible.

  • Local scope: Inside a function
  • Global scope: Outside all functions
  • Enclosing scope: A function inside another function

Here's a visual diagram to help you understand variable scopes:

2.The global Keyword

The global keyword is used to modify a variable outside of the current function, specifically the one in the global scope.

Normally, assigning to a variable inside a function creates a local variable. If you want to change a variable that exists at the global(module) level, you need to declare it global.

Example 1:

x = 10

def change_global():
    global x
    x = 20

change_global()
print(x)  # Output: 20

Example 2:

counter = 0

def increment():
    global counter
    for _ in range(5):
        counter += 1

increment()
print(counter)  # Output: 5

Example 3:

flag = False

def activate():
    global flag
    flag = True

activate()
print(flag)  # Output: True

What's happening here?

Even though x, counter, or flag were defined outside the function, we can change their values inside the function using global. Without the global keyword, Python would treat them as new local variables.

3. The nonlocal Keyword

The nonlocal keyword is used in nested functions. It allows you to modify a variable in the enclosing (but not global) scope. This is useful when you want to update a variable in an outer function from within an inner function.

Example 1:

def outer():
    y = 5

    def inner():
        nonlocal y
        y = 10

    inner()
    print(y)  # Output: 10

outer()

Example 2:

def outer():
    msg = "Hello"

    def inner():
        nonlocal msg
        msg += ", World!"

    inner()
    print(msg)  # Output: Hello, World!

outer()

Example 3:

def counter_maker():
    count = 0

    def counter():
        nonlocal count
        count += 1
        return count

    return counter

c = counter_maker()
print(c())  # Output: 1
print(c())  # Output: 2

What's happening here?

In all of these examples, the inner function modifies a variable in the outer function using nonlocal. This would not be possible without declaring the variable as nonlocal.

Comments

Popular

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...