Loading...

Go Back

Next page
Go Back Course Outline

Python Full Course


Advanced Python Concepts

1. Iterators and Generators

Understanding Iterators

An iterator is any object in Python which implements two methods:

  • __iter__()
  • __next__()
numbers = [1, 2, 3]

iterator = iter(numbers)  # Getting an iterator

print(next(iterator))  # Output: 1
print(next(iterator))  # Output: 2
print(next(iterator))  # Output: 3
1 2 3

Creating Custom Iterators

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

# Using the custom iterator
for num in Counter(1, 3):
    print(num)
1 2 3

Generators and yield keyword

def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()

print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 3
1 2 3

Generator Expressions

squares = (x*x for x in range(4))

for sq in squares:
    print(sq)
0 1 4 9


2. Decorators

Understanding Decorators

def decorator(func):
    def wrapper():
        print("Before the function call")
        func()
        print("After the function call")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()
Before the function call Hello! After the function call

Creating Custom Decorators

def greet_decorator(func):
    def wrapper():
        print("Good Morning!")
        func()
    return wrapper

@greet_decorator
def greet_name():
    print("Emmanuel")

greet_name()
Good Morning! Emmanuel

Decorators with Arguments

def smart_divide(func):
    def wrapper(a, b):
        print(f"Dividing {a} by {b}")
        if b == 0:
            print("Cannot divide by zero!")
            return
        return func(a, b)
    return wrapper

@smart_divide
def divide(a, b):
    return a / b

print(divide(10, 2))
print(divide(5, 0))
Dividing 10 by 2 5.0 Dividing 5 by 0 Cannot divide by zero! None

3. Context Managers

The with Statement

with open('example.txt', 'w') as file:
    file.write("Hello Emmanuel!")
The file closes automatically when with block ends.

Creating Custom Context Managers

class MyContext:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Exiting the context")

with MyContext():
    print("Inside the context")
Entering the context Inside the context Exiting the context

4. Concurrency and Parallelism

Threading Example

import threading

def greet():
    print("Hello from thread")

thread = threading.Thread(target=greet)
thread.start()
thread.join()
Hello from thread

Multiprocessing Example

import multiprocessing

def greet():
    print("Hello from process")

process = multiprocessing.Process(target=greet)
process.start()
process.join()
Hello from process

Asynchronous Programming (asyncio)

import asyncio

async def say_hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World!")

asyncio.run(say_hello())
Hello (wait 1 second) World!

5. Regular Expressions

Pattern Matching

import re

pattern = r"hello"
text = "hello world"

match = re.search(pattern, text)
print(match.group())
hello

Search and Extract Example

import re

text = "My phone number is 123-456-7890"

phone = re.search(r'\d{3}-\d{3}-\d{4}', text)
print(phone.group())
123-456-7890

Replace Example

new_text = re.sub(r'\d', '*', text)
print(new_text)
My phone number is ***-***-****


6. Type Hinting

Using Type Hints

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

print(add_numbers(3, 4))
7

Type Hinting Collections

from typing import List

def total(numbers: List[int]) -> int:
    return sum(numbers)

print(total([1, 2, 3]))
6
Static Analysis Tools: Use mypy to check type hints:
pip install mypy
mypy your_script.py

⭐ Final Notes

  • Iterators and Generators save memory (good for large data)
  • Decorators make your code DRY (Don't Repeat Yourself)
  • Context Managers make sure resources are properly closed
  • Concurrency makes your code faster when doing many tasks
  • Regular Expressions are powerful for text processing
  • Type Hinting improves code clarity and works great with large projects
Go Back

Next page