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

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

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...