Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“¦ Python Namespace: Complete Guide with Examples

Python Namespace - Complete Guide

Namespaces are like containers that hold names and their associated objects in Python.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
We are a team of Python developers, data engineers and data scientists with years of real-world experience. We have built production applications. We have tackled complex problems. We have helped teams ship better code. What drives us? Teaching — especially that moment when things finally click. Our tutorials focus on practical examples and honest guidance. Whether you are just starting out or leveling up we are here to make Python genuinely useful.
šŸ“‘ On this page:
  • What is a Namespace?
  • Types of Namespaces
  • Built-in Namespace
  • Global Namespace
  • Local Namespace
  • The LEGB Rule
  • Namespace vs Scope
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What a namespace is — understanding name containers in Python
  • Types of namespaces — built-in, global, and local
  • Built-in namespace — Python's predefined names
  • Global namespace — module-level names
  • Local namespace — function-level names
  • The LEGB rule — how Python resolves names
  • Namespace vs Scope — understanding the difference
  • Hands-on practice with the interactive editor

What is a Namespace?

A namespace in Python is a container that holds a set of identifiers (names) and their corresponding objects. Think of it like a dictionary where the keys are names and the values are the objects they refer to.

Namespaces help Python organize and manage names so that they don't conflict with each other. For example, you can have a variable named x in one function and another variable named x in a different function — they don't conflict because they exist in different namespaces.

# Different namespaces allow the same name to be used
x = 10  # Global namespace

def my_function():
    x = 20  # Local namespace (different from global x)
    print(f"Local x: {x}")

my_function()
print(f"Global x: {x}")

# Output:
# Local x: 20
# Global x: 10

šŸ’” Key insight: A namespace is like a filing cabinet where each drawer (namespace) can have a file with the same name (variable) without conflict.

Types of Namespaces

Python has three main types of namespaces:

šŸ”§ Built-in

Contains Python's built-in functions and exceptions

šŸŒ Global

Contains names defined at the module level

šŸ“¦ Local

Contains names defined inside a function

1. Built-in Namespace

The built-in namespace contains Python's built-in functions, exceptions, and objects. These are available everywhere in your Python code without any import.

# Built-in namespace examples
print()  # Built-in function
len()    # Built-in function
int()    # Built-in function
str()    # Built-in function

# View built-in names
import builtins
print(dir(builtins)[:10])  # Shows first 10 built-in names

2. Global Namespace

The global namespace contains names defined at the module level — outside any function or class. These names are accessible throughout the module.

# Global namespace examples
name = "Python"      # Global variable
version = 3.12       # Global variable

def show_global():
    print(name)      # Accessing global variable

show_global()
print(version)

# Output:
# Python
# 3.12

3. Local Namespace

The local namespace contains names defined inside a function. These names are only accessible within that function.

# Local namespace examples
def calculate():
    a = 10          # Local variable
    b = 20          # Local variable
    return a + b

result = calculate()
print(result)       # 30

# a and b are not accessible outside the function
# print(a)  # NameError: name 'a' is not defined

4. The LEGB Rule

Python uses the LEGB rule to resolve names when they are referenced. LEGB stands for:

L - Local

Names defined inside a function

E - Enclosing

Names in outer functions

G - Global

Names at the module level

B - Built-in

Python's built-in names

# LEGB Rule Example
x = "global"      # Global

def outer():
    x = "enclosing"  # Enclosing
    
    def inner():
        x = "local"  # Local
        print(f"Local x: {x}")
        print(f"Built-in: {len('hello')}")
    
    inner()

outer()

# Output:
# Local x: local
# Built-in: 5

5. Namespace vs Scope

While namespaces and scopes are related, they are different concepts:

# Namespace vs Scope Example
# Namespace: The container of names
# Scope: The region where a name is accessible

global_var = "global"

def my_function():
    local_var = "local"     # Local namespace
    print(global_var)       # Can access global scope
    print(local_var)        # Can access local scope

my_function()
# print(local_var)  # Error - local_var is not in this scope

Try It Yourself!

Experiment with namespaces directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
NAMESPACE DEMONSTRATION
========================================

1. LOCAL VARIABLE:
I am local

2. ENCLOSING VARIABLE:
I am enclosing

3. GLOBAL VARIABLE:
I am global

4. BUILT-IN FUNCTION:
Built-in len: 5

========================================
NAMESPACE DIFFERENCES
========================================
Global x: 10
Local x: 20
Local x in function2: 30

āœ… Different namespaces allow same names without conflict!
šŸ†

šŸŽ‰ You've Mastered Python Namespace!

You understand built-in, global, and local namespaces, the LEGB rule, and the difference between namespace and scope. These concepts are fundamental to Python programming.

Quick Quiz – Test Your Knowledge

Let's see what you've learned about Python namespaces:

1. What does LEGB stand for in Python?
2. Which namespace contains Python's built-in functions like print()?
3. What is the scope of a local variable defined inside a function?

Frequently Asked Questions

šŸ¤” What's the difference between namespace and scope? ā–¼

A namespace is a container that holds names and their objects. A scope is the region of a program where a name is accessible. A namespace defines the names; scope defines where those names can be used.

šŸ”§ How does Python resolve variable names? ā–¼

Python uses the LEGB rule: Local → Enclosing → Global → Built-in. It searches these namespaces in order until it finds the name or raises a NameError.

šŸ“‚ Can I modify a global variable inside a function? ā–¼

Yes, you can use the global keyword inside a function to modify a global variable. Without it, Python creates a new local variable with the same name.

šŸ“Š What is an enclosing namespace? ā–¼

An enclosing namespace belongs to an outer (enclosing) function. It's used when you have nested functions — the inner function can access variables from the outer function's namespace.

šŸ“š Where to Go From Here

Now that you understand Python namespaces, here are some related topics to explore:

🌐 Global & Local Variables

Learn about variable scope

šŸ“ Functions

Learn about functions in Python

šŸ“¦ Modules

Learn about Python modules

šŸ“– Related Tutorials
  • Global, Local, and Nonlocal
  • Introduction to Functions
  • Variables and Identifiers
  • Introduction to Modules
Previous: Simple Python Scripts Next: Assignments →