Small Experiments in the Python Interpreter
An interactive interpreter helps isolate an expression or check a language rule. Keep enough context to replay the experiment in a fresh session.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Start with a clean binding
Typing values = [4, 7] creates a list whose later changes persist in the session. After experimenting with appending an item, a new test using the same name has extra input unless you initialize it again. Replaying an execution trace from a fresh session makes those hidden dependencies visible.
Distinguish display from program output
At the interpreter prompt, an expression such as len([4, 7]) is normally displayed as two. The same expression as a statement in a file produces no visible result unless some code writes it. This follows the distinction between computing a value and emitting output. Save the initialization and the assertion together once the experiment explains the behavior.[1][2]
Use a fresh experiment for a disputed operation
A small interpreter session can reveal exactly what type and value one operation gives. For a string "2.50", try the conversion intended for whole counts and the one intended for decimal measurements separately. Record the precise accepted spelling and result. An experiment with a prepared variable can be copied into a test only if the initialization is included. Otherwise, a past assignment in the session can make the result differ from the script. See reproducing a run.
The differences between print(value), repr(value), and simply evaluating value can matter. An interactive console may display an expression result while an ordinary file discards that result when used as a statement. Displaying a representation explains why escaped characters can be easier to inspect in one form.
Convert an investigation into a small check
Suppose a list looks unexpectedly longer after you've tried the same code twice. Start a fresh interpreter and create the list once. Perform exactly one append and check the new result, then repeat from a new independent list. This separates a repeatable operation from accumulated state. When two names could share that list, make the second name explicit in the setup. Consult state traces for how to record which object changed.
A saved test can use a small known example and an assertion on the actual returned value. That way, the next person can run the result without needing to reconstruct the sequence of interactive experiments.