QA
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→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?