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
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)
yield
keyworddef my_generator(): yield 1 yield 2 yield 3 gen = my_generator() print(next(gen)) # 1 print(next(gen)) # 2 print(next(gen)) # 3
squares = (x*x for x in range(4)) for sq in squares: print(sq)
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()
def greet_decorator(func): def wrapper(): print("Good Morning!") func() return wrapper @greet_decorator def greet_name(): print("Emmanuel") greet_name()
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))
with
Statementwith open('example.txt', 'w') as file: file.write("Hello Emmanuel!")
with
block ends.
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")
import threading def greet(): print("Hello from thread") thread = threading.Thread(target=greet) thread.start() thread.join()
import multiprocessing def greet(): print("Hello from process") process = multiprocessing.Process(target=greet) process.start() process.join()
asyncio
)import asyncio async def say_hello(): print("Hello") await asyncio.sleep(1) print("World!") asyncio.run(say_hello())
import re pattern = r"hello" text = "hello world" match = re.search(pattern, text) print(match.group())
import re text = "My phone number is 123-456-7890" phone = re.search(r'\d{3}-\d{3}-\d{4}', text) print(phone.group())
new_text = re.sub(r'\d', '*', text) print(new_text)
def add_numbers(a: int, b: int) -> int: return a + b print(add_numbers(3, 4))
from typing import List def total(numbers: List[int]) -> int: return sum(numbers) print(total([1, 2, 3]))
mypy
to check type hints:
pip install mypy mypy your_script.py