Core Module
12 min forge
Python Functional Features
Lambdas, Decorators, and Higher-Order Functions.
Python Functional Features
π What is it
Python supports multiple programming paradigms, including functional programming. It treats functions as First-Class Citizens, meaning functions can be passed as arguments, returned from other functions, and assigned to variables.
ποΈ Core Concepts
- Lambda Functions: Small anonymous functions defined with the
lambdakeyword. - Decorators: A design pattern that allows you to modify the behavior of a function or class without permanently modifying it.
- Map, Filter, Reduce: Common higher-order functions used to process collections.
- List Comprehension: A concise way to create lists based on existing lists.
β‘ Decorators
Decorators are often used for logging, access control, or timing functions.
π» Code example
python Standard# Lambda square = lambda x: x * x # Decorator def log_execution(func): def wrapper(*args, **kwargs): print(f"Executing {func.__name__}...") return func(*args, **kwargs) return wrapper @log_execution def say_hello(): print("Hello!") say_hello()
β Common mistakes
- Lambda complexity: Trying to cram too much logic into a lambda (use a named function if it's more than one line).
- Decorator closure: Forgetting to use
functools.wrapsto preserve the metadata (like__name__) of the original function. - Overusing
map: Usingmapandfilterwhen a list comprehension would be more readable.