Sub topic 13
When to Leave the Shell and Write a File
This chapter assumes you can start the shell, define functions and loops at the ... prompt, import modules, and read a traceback. It covers where the shell stops being the right tool and how to move your work into a file without losing what you learned.
What the shell does well
The shell gives you an answer after every statement. That makes it a good place to check what a function returns, test a regular expression, or see how a library call behaves. Session state also persists after an exception, so you can keep poking at the same objects.
Where the shell gets in the way
Several limits show up as experiments grow.
- Nothing is saved. Close the session and your definitions are gone. Command history may recall lines, but it does not rebuild your state.
- Multi-line blocks are hard to fix. In most versions of the shell, an error inside a block means you retype the block. Newer versions let you recall a whole block for editing, but a file is still easier.
- Hidden state misleads you. A variable you set ten minutes ago may still exist, so code can work in the session and fail in a fresh run. A function you deleted from your notes may still be defined.
- Others cannot run it. A session cannot be reviewed, committed, or tested.
Signs it is time to move
Move your code into a file when any of these is true:
- You have retyped or recalled the same block more than twice.
- The code spans more than one function or needs to be called with several inputs.
- You want to keep it, share it, or run it again tomorrow.
- A result depends on the order in which you ran earlier statements.
Moving code to a file
Suppose you built a small function in the shell:
>>> def average(values):
... return sum(values) / len(values)
...
>>> average([2, 4, 9])
5.0Copy the definition into stats.py, and add the checks you ran by hand:
def average(values):
return sum(values) / len(values)
if __name__ == "__main__":
print(average([2, 4, 9]))
print(average([10]))The if __name__ == "__main__": block runs only when you start the file directly. It does not run when another file imports stats. This lets one file serve as both a script and a module.
Run it from a terminal:
python3 stats.pyThe output is:
5.0
10.0Because the file runs from the top in a new process, it cannot depend on leftover names. That is the clean-start check described above.
Keeping the shell as a companion
Leaving the shell does not mean abandoning it. Use the file for the code you want to keep, and the shell to explore it.
- Run
python3 -i stats.pyto execute the file and then stay at the prompt withaveragedefined. - Use
importlib.reload()after you edit a module you imported in a running session. - Set
PYTHONSTARTUPto a file of helper imports you want in every session.
A common loop is to edit the file, run it, try a surprising input in the shell, then put the fix back into the file.
Turning shell experiments into tests
Once you know what the right answer is, record it. The values you checked by hand become assertions:
from stats import average
assert average([2, 4, 9]) == 5.0
assert average([10]) == 10.0
print("ok")Now the check runs without you watching the output. For larger projects, a test framework such as pytest does the same job with better reports.
Exercise
You tested a function in the shell and it worked. After moving it to a file and running python3 file.py, you get a NameError. What is the most likely cause, and how do you avoid it?
Show answer
The function relied on a name defined earlier in the session, such as a variable or an import, that the file does not define. Put every needed import and definition in the file, and run it from a clean start to confirm it works on its own.
Exercise
Why should the test calls in stats.py sit under if __name__ == "__main__":?
Show answer
The block runs only when the file is started directly. When another file imports stats, the calls are skipped, so importing does not print anything or run the checks.