Inspecting Objects with the inspect Module
The standard `inspect` module provides live introspection of active objects. You can inspect call signatures, read parameter types, and extract source code dynamically 🔬.
import inspect
def send_alert(user_id: int, message: str = "Warning") -> bool:
"""Sends priority dispatch."""
return True
sig = inspect.signature(send_alert)
print(sig) # (user_id: int, message: str = 'Warning') -> bool 🔬
for name, param in sig.parameters.items():
print(f"Param: {name}, Default: {param.default}")
# 68. Inspecting Objects with the inspect Module The standard `inspect` module provides live introspection of active objects. You can inspect call signatures, read parameter types, and extract source code dynamically 🔬. ```python import inspect def send_alert(user_id: int, message: str = "Warning") -> bool: """Sends priority dispatch.""" return True sig = inspect.signature(send_alert) print(sig) # (user_id: int, message: str = 'Warning') -> bool 🔬 for name, param in sig.parameters.items(): print(f"Param: {name}, Default: {param.default}") ``` Frameworks like FastAPI and Pydantic use `inspect.signature` under the hood to automatically validate incoming JSON against function signatures! 🔬 --- ### Question Which function in the `inspect` module retrieves the callable parameters and return annotation? 🧠- [ ] a. `inspect.signature()` 🔬 - [ ] b. `inspect.getparams()` - [ ] c. `inspect.getbytecode()` - [ ] d. `inspect.extract()` --- ### Challenge Import `inspect`. Define `def compute(a, b=10): pass`. Use `inspect.signature(compute)` and print `list(sig.parameters.keys())`. 🎯 <details> <summary>Solution</summary> ```python import inspect def compute(a, b=10): pass sig = inspect.signature(compute) print(list(sig.parameters.keys())) ``` </details>