Python Advanced Python

Explore comprehensions, generators, decorators, and context managers.

After learning Python basics such as variables, loops, functions, and Object-Oriented Programming, you are ready to explore advanced features. These tools help you write cleaner, more efficient, and professional code.

Advanced Python is not a completely new language. It introduces powerful tools that make programming easier and reduce the amount of repetitive code you need to write.

In this lesson, you will learn about iterators, generators, decorators, context managers, type hints, dataclasses, and named tuples. You do not need to master all of them immediately, but understanding the basics will prepare you for real-world Python development.

Iterators

An iterator is an object that lets you access items one at a time instead of all at once. Many Python objects, including lists, tuples, and strings, are iterable.

Python
fruits = ["Apple", "Banana", "Orange"]

iterator = iter(fruits)

print(next(iterator))
print(next(iterator))
print(next(iterator))

Output

devbrainbox.local/output
Apple
Banana
Orange

The iter() function creates an iterator, and next() returns one item at a time. Iterators are useful with large collections because they process data gradually.

Generators

A generator is a simple way to create an iterator. Instead of using return to finish with one result, a generator uses yield to produce a sequence of values over time.

Python
def count_numbers():
    for number in range(1, 6):
        yield number

for value in count_numbers():
    print(value)

Output

devbrainbox.local/output
1
2
3
4
5

Generators are memory-efficient because they produce values only when needed instead of storing every value at once.

Decorators

A decorator is a function that adds extra functionality to another function without changing its original code.

Python
def welcome(func):
    def wrapper():
        print("Welcome!")
        func()
    return wrapper

@welcome
def greet():
    print("Hello, Python!")

greet()

Output

devbrainbox.local/output
Welcome!
Hello, Python!

Decorators are commonly used for logging, authentication, timing functions, and access control.

Context Managers

A context manager helps manage resources automatically. The most common example is working with files. Instead of manually opening and closing a file, use the with statement.

Python
with open("notes.txt", "r") as file:
    print(file.read())

When the with block finishes, Python automatically closes the file. Context managers help prevent resource leaks and make your code safer.

Type Hints

Python is dynamically typed, but you can add type hints to improve code readability.

Python
def add(a: int, b: int) -> int:
    return a + b

print(add(10, 5))

These hints indicate that both parameters and the return value should be integers. Python does not enforce these types at runtime, but type hints help developers, editors, and static-analysis tools detect mistakes.

Dataclasses

A dataclass is a convenient way to create a class that mainly stores data. Without a dataclass, you would need to write common setup methods manually.

Python
from dataclasses import dataclass

@dataclass
class Student:
    name: str
    age: int

student = Student("Alice", 20)

print(student)

Output

devbrainbox.local/output
Student(name='Alice', age=20)

Dataclasses automatically create useful methods such as __init__() and __repr__(), reducing repetitive code.

Named Tuples

A named tuple is like a regular tuple, but each value has a meaningful name.

Python
from collections import namedtuple

Student = namedtuple("Student", ["name", "age"])
student = Student("John", 21)

print(student.name)
print(student.age)

Output

devbrainbox.local/output
John
21

Named tuples make code easier to read because you access values by name instead of numeric indexes.

Why Learn Advanced Python?

These advanced features help you write code that is:

  • Shorter and cleaner
  • Easier to understand
  • More memory-efficient
  • Easier to maintain
  • Better suited for large projects

Many popular Python libraries and frameworks, such as Django, Flask, FastAPI, and Pandas, use these features. As you continue learning Python, you will see these concepts more often.

When Should You Use These Features?

  • Use iterators and generators when working with large amounts of data.
  • Use decorators when you want to add common functionality to multiple functions.
  • Use context managers whenever you work with files or other resources.
  • Use type hints to improve readability and reduce mistakes.
  • Use dataclasses when creating classes that mainly store information.
  • Use named tuples when you need lightweight, readable data structures.

You do not need advanced features for every program. Start with the basics and gradually use these tools as your projects become more complex.