Loading notes...
Loading notes...
B.Tech • Chapter 5
B.Tech level module on Functions, Generators, & Decorators.
Functions in Python are First-Class Objects, meaning they can be passed as arguments, returned from other functions, and assigned to variables. This enables functional programming paradigms and metaprogramming through Decorators.
Advanced Engineering Concepts
Generators use the 'yield' keyword to return an iterator that computes one value at a time. This is lazy evaluation, which is extremely memory efficient for large datasets (e.g., reading gigabytes of log files) because it avoids loading everything into RAM at once. Decorators are wrappers that modify the behavior of a function dynamically, heavily used in web frameworks like Flask and Django.
Code Implementation
# Generator for large sequences
def fibonacci_gen(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
# Decorator for timing execution
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Execution time: {time.time() - start}s")
return result
return wrapper
@timer_decorator
def heavy_computation():
sum(i*i for i in range(1000000))
heavy_computation()