Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Variable Scope and Object Lifetime

Functions · Tutorial 21

Python Variable Scope and Object Lifetime

Understand local, global, and nonlocal scope, when variables are created, and why modifying globals inside functions is risky.

Open the compilerPractice exercises
intermediate8 min readUpdated November 19, 20264 learning goals
On this page
  1. Local scope
  2. Reading globals
  3. Modifying globals
  4. Enclosing scope and nonlocal
  5. Name resolution example
  6. Object lifetime
  7. Practice

What you will learn

  • Distinguish local and global names
  • Read globals safely and use the global keyword sparingly
  • Use nonlocal for closures
  • Explain when objects become unreachable
Before this lesson: Python Functions: Define, Call, and Return Values, Python Function Arguments: Defaults, Keyword, and *args

Scope determines where a name can be used. Python resolves names using the local, enclosing, global, and built-in scopes, often remembered as LEGB.

Local scope#

Names assigned inside a function are local by default:

Python
def calculate():
    result = 42
    return result


print(calculate())
# print(result)  # NameError: result is not defined

The local name exists only while the function runs. Each call gets a fresh local namespace.

Reading globals#

A function can read a global name without declaring it:

Python
site_name = "ILoveCompiler"


def banner():
    print(f"Welcome to {site_name}")


banner()

Reading works because Python falls back to the module scope when a name is not local.

Modifying globals#

Assigning to a global name inside a function creates a local name unless you declare global:

Python
counter = 0


def increment():
    global counter
    counter += 1


increment()
print(counter)  # 1

This works, but global mutable state makes programs harder to reason about and test. Prefer passing values in and returning results:

Python
def increment(value):
    return value + 1


counter = increment(counter)

The second version makes the data flow explicit.

global is rarely the right tool

If you find yourself using global to share state between many functions, consider a class, a configuration object, or explicit function arguments instead. Global state creates hidden dependencies.

Enclosing scope and nonlocal#

A nested function can read names from its enclosing function. To rebind them, use nonlocal:

Python
def make_counter():
    count = 0

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

    return increment


counter = make_counter()
print(counter())  # 1
print(counter())  # 2

make_counter returns the inner function, which keeps a reference to count. This is a closure. The count variable survives between calls because the inner function still refers to it.

Without nonlocal, count += 1 would create a new local variable and raise UnboundLocalError.

Name resolution example#

Python
value = "global"


def outer():
    value = "enclosing"

    def inner():
        print(value)

    inner()


outer()
Expected output

enclosing

inner reads the closest enclosing binding. If it assigned to value, that name would become local unless declared nonlocal.

Object lifetime#

CPython uses reference counting plus a garbage collector. An object stays alive while something references it. When the last reference disappears, it becomes eligible for collection.

Python
def make_greeting():
    text = "Hello"
    return text


message = make_greeting()
print(message)

The string survives the function call because the returned reference is stored in message.

You rarely manage memory manually in Python. Cycles are handled by the garbage collector, and files or network connections should still be closed with with statements or finally blocks.

Practice#

Write make_accumulator() that returns a function. Each call to the returned function adds its argument to a running total and returns the new total. Use nonlocal. Then rewrite a small global counter example as a function that takes and returns the count.

Previous tutorialPython Function Arguments: Defaults, Keyword, and *argsNext tutorialPython Error Handling with try, except, else, and finally

Related tutorials

intermediate

Python Error Handling with try, except, else, and finally

Read tracebacks, catch specific exceptions, raise your own errors, and clean up resources reliably.

9 min read
intermediate

Python Classes and Objects: A Practical Introduction

Define classes, create objects, use __init__ and methods, and model state without overengineering.

10 min read

On this page

  1. Local scope
  2. Reading globals
  3. Modifying globals
  4. Enclosing scope and nonlocal
  5. Name resolution example
  6. Object lifetime
  7. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.