Advanced Call Techniques
Decorator-Based Function Calls
Function Decorators
def performance_tracker(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function {func.__name__} took {end - start} seconds")
return result
return wrapper
@performance_tracker
def complex_calculation(n):
return sum(i**2 for i in range(n))
complex_calculation(10000)
Partial Function Application
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(4)) ## Output: 16
print(cube(3)) ## Output: 27
Method Resolution Techniques
Technique |
Description |
Use Case |
Method Resolution Order |
Determines method inheritance |
Complex class hierarchies |
Super() Function |
Calls parent class methods |
Multilevel inheritance |
Metaclass Manipulation |
Dynamic method creation |
Advanced class generation |
class DynamicMethodMeta(type):
def __new__(cls, name, bases, attrs):
attrs['dynamic_method'] = lambda self: print("Dynamically created method")
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=DynamicMethodMeta):
pass
obj = MyClass()
obj.dynamic_method() ## Output: Dynamically created method
Advanced Call Flow
graph TD
A[Function Call Initiated] --> B{Decorator Present?}
B -->|Yes| C[Apply Decorator]
B -->|No| D[Direct Execution]
C --> E[Execute Original Function]
D --> E
E --> F[Return Result]
Reflection and Introspection
import inspect
def analyze_function(func):
signature = inspect.signature(func)
parameters = signature.parameters
print("Function Name:", func.__name__)
print("Parameters:")
for name, param in parameters.items():
print(f"- {name}: {param.kind}")
def example_function(x: int, y: str = 'default'):
pass
analyze_function(example_function)
Context Managers for Function Calls
from contextlib import contextmanager
@contextmanager
def function_context(func):
print(f"Entering function: {func.__name__}")
try:
yield func
finally:
print(f"Exiting function: {func.__name__}")
@function_context
def greet(name):
return f"Hello, {name}!"
result = greet("LabEx User")
print(result)
Key Advanced Techniques
- Metaprogramming
- Dynamic method generation
- Function introspection
- Context-aware function calls
LabEx emphasizes that advanced function call techniques require careful implementation and deep understanding of Python's dynamic capabilities.