Sub topic 3
Reading Tracebacks and Keeping Your Session State
Assume you know basic Python syntax, can run commands in a terminal, and have Python 3 installed.
A traceback shows where an exception occurred and why. Read it from the bottom up. The last line gives the exception type and message. Earlier lines show the path through your code.
>>> int("abc")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'abc'
>>> x = 5
>>> x
5The exception ends the failing statement, not the whole REPL session. Variables created before the error remain available. A variable assigned before a later failing operation also keeps its earlier value. Check important state instead of assuming an interrupted statement completed.
Editing Lines and Using History
Most Python shells support line editing through your terminal. Use the Up and Down arrow keys to revisit commands, then edit and run them again. Ctrl-P and Ctrl-N often move backward and forward through history. The exact keys depend on your terminal and Python build.
History is useful for repeating experiments, but it is not a reliable record of a program. Copy successful code into a file when it becomes important.
Reloading an Edited Module
An imported module is stored in sys.modules. Importing it again normally reuses the existing module instead of reading the file again. During an experiment, reload it explicitly:
>>> import importlib
>>> import mymodule
>>> # Edit mymodule.py in your editor.
>>> importlib.reload(mymodule)
<module 'mymodule' ...>Reloading re-executes the module's top-level code. Existing objects imported with from mymodule import name may still refer to old definitions, so prefer import mymodule and use mymodule.name.
Starting Interactively After a Script
Use -i to run a script and then keep its variables in an interactive session:
python3 -i script.pyPYTHONSTARTUP names a Python file that Python runs before an interactive session starts. It can define helpful functions, but it does not run when Python executes a script. Keep startup files small because they change every interactive session.
When to Leave the Shell
The REPL is best for small questions and quick probes. Move code into a file when it needs multiple runs, tests, version control, or collaboration. A file also prevents useful work from being lost when you close the session.
Exercise
After x = 5 succeeds and int("abc") raises an exception, what should x contain?
Show answer
x should still contain 5, because the failed statement does not erase earlier session state.