Functions in Python
Complete and in-depth guide to Python functions: creation, execution flow, parameters, closures, decorators, higher-order functions, callable objects, and advanced function behavior.
Function Basics & Execution Flow
Functions encapsulate reusable logic. Execution jumps into the function when called and returns back after completion.
Creating and Calling a Function
Define once, call many times.
Execution Flow Between Functions
Understand call stack behavior.
Parameters & Arguments
Python supports positional, keyword, default, variable-length, positional-only, and keyword-only parameters.
Default Parameters
Fallback values if argument is missing.
Keyword Arguments
Order-independent calling.
*args and **kwargs
Variable number of arguments.
Positional-only & Keyword-only Parameters
Advanced parameter control.
Type Hints & Annotations
Python allows optional type hints. They improve readability and tooling but are not enforced at runtime.
Basic Type Hints
Annotate parameters and return type.
First-Class Functions
In Python, functions are first-class objects. They can be stored, passed, and returned.
Assigning Function to Variable
Functions behave like objects.
Lambda Function
Small anonymous function.
Closures
A closure occurs when an inner function remembers variables from outer scope.
Stateful Closure
Maintain private state.
Decorators
Decorators wrap functions to extend or modify behavior.
Basic Decorator
Wrap function execution.
Higher Order Functions
A higher-order function accepts a function as argument or returns one.
Implementing map() Manually
Transform list elements.
Callable Objects
An object is callable if it can be called like a function using parentheses.
Using callable()
Check if object is callable.
Making Class Callable
Using __call__ method.
Immediately Invoked Functions (IIFE)
Python does not have a special IIFE syntax like JavaScript, but since functions are first-class objects, we can define and call them immediately using lambda expressions or by defining and calling them in the same block.
1. IIFE using lambda
Define and call an anonymous function instantly.
2. IIFE with Arguments
Pass arguments to the immediately invoked function.
3. Simulating IIFE using def
Define, execute, and remove function immediately.
4. When Should You Use IIFE?
Python philosophy on IIFE usage.