Intermediate LevelPython
How do you inspect live object signatures, source code, and caller stack frames using the inspect module?
❓ Interview Prompt: Explain `inspect` module, `inspect.signature()`, `inspect.getsource()`, `inspect.stack()`, and runtime metaprogramming.
The 'inspect' module provides low-level introspection capabilities for examining live functions, classes, and stack frames:
Use Cases:
•
'inspect.signature(func)': Inspects parameter signatures and type annotations (used by FastAPI for dependency injection!).
•
'inspect.getsource(func)': Returns raw source code text of live functions.
Code Implementation Example
python
import inspect
def user_handler(user_id: int, role: str = 'user') -> dict:
return {'user_id': user_id, 'role': role}
# Inspect function parameters dynamically
sig = inspect.signature(user_handler)
for name, param in sig.parameters.items():
print(f'Param: {name}, Annotation: {param.annotation}, Default: {param.default}')💡Inspecting live function signatures dynamically via inspect.signature().
🎯 Interview Key Takeaway
Use the inspect module to build frameworks that require dynamic dependency injection and signature validation.
#inspect#Introspection#Signatures#Intermediate
Back to all Python Questions→