Introspection in Python
Asking an object about itself: signature, docstring, source, members.
import inspect
def score(tpm: float, target: float = 90.0, *, strict: bool = False) -> int:
"""Stars for a run."""
return 3 if tpm >= target else 1
signature = inspect.signature(score)
print(signature)
print([p.name for p in signature.parameters.values()])
print(signature.parameters["target"].default)
print(inspect.getdoc(score))
print(len(inspect.getsource(score).splitlines()))
How it works
signaturereads the parameters and their defaults.getdocreturns the docstring, cleaned up.getsourcereturns the code, when it is available.
Keywords and builtins used here
booldefelsefloatforifintlenprintreturnscore
The run, in numbers
- Lines
- 14
- Characters to type
- 385
- Tokens
- 105
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 57 seconds.
Step 2 of 4 in Measuring & introspecting, step 36 of 41 in Domain tools.