Sub topic 13
When to Leave the Shell and Write a File
This chapter assumes you can start the interactive shell, read the echoed output, write multi-line blocks, and read tracebacks. It also assumes you know python3 -i and importlib.reload() from earlier chapters. Here you decide when a shell session has stopped being the right tool, and you move the code into a file without losing what you learned.
What the shell is good at
The shell gives you feedback after every statement. That makes it the fastest way to do these things:
- Check what a function returns for one input.
- Look at an unfamiliar object with
type(),dir(), andhelp(). - Try a string method, a slice, or a format specifier.
- Reproduce a small bug with a few lines of setup.
These jobs share one trait: you can discard the code afterward. The shell is a scratchpad, and most of its limits come from the fact that it keeps nothing except what is in memory.
Where the shell stops working for you
Nothing is saved as a program
Your history is a record of everything you typed, including typos, failed attempts, and lines you would not run again. Replaying it does not give you a clean program. Some distributions of the shell keep history between sessions, but that file mixes working and broken lines, and it does not keep the output.
Hidden state makes results depend on history
Each statement runs against whatever names exist at that moment. The result can depend on lines you typed twenty minutes ago and forgot.
>>> data = [3, 1, 2]
>>> data.sort()
>>> def smallest():
... return data[0]
...
>>> smallest()
1smallest() works only because a global named data exists. If you copy the function into a new file and forget to define data, you get a NameError. The shell cannot tell you that, because the name was there the whole time. A file run from the top in a fresh process tests whether your code actually stands on its own.
Editing multi-line code is awkward
Once you press Enter on a finished block, you cannot go back and fix line two of a function. You recall the block from history and edit it as a unit, or you retype it. Pasting blocks is also fragile. A blank line inside a pasted function can end the block early, and mixed tabs and spaces cause indentation errors.
A failed block leaves partial state
An exception ends only the failing statement. If a loop fails on the fifth iteration, the first four have already run, and any names they changed stay changed. You must work out which changes happened before you retry, or restart the session.
Reloading has gaps
importlib.reload() re-executes a module, but it does not update references you already hold. This is a common source of confusing behavior.
import importlib
import mymodule
from mymodule import greet
# After you edit mymodule.py:
importlib.reload(mymodule)
mymodule.greet("Ada") # runs the new code
greet("Ada") # still runs the old function objectThe name greet in your session points to the function object that existed when you ran from mymodule import greet. Reload creates a new function inside mymodule but does not rebind your greet. Objects created from an old class also keep the old class. If you see behavior that does not match your edit, you are probably running stale objects. Restarting the shell removes the question entirely.
There is no structure for checking results
In the shell you eyeball the output each time. A file can hold assertions that you rerun after every change. That is the difference between "it worked when I tried it" and "it still works."
Signals that it is time to write a file
| Signal | Why a file helps |
|---|---|
| You retype or recall the same block more than twice | A file runs the whole block with one command. |
| A block is longer than about ten lines | You can edit any line in an editor. |
| You need the same setup every session | The file holds the setup in order. |
| Results seem to differ from what the code says | A fresh process removes hidden state. |
| You want to keep, share, or review the code | A file works with version control. |
| You want to check that behavior stays correct | A file can hold tests. |
| Another program must call your code | A module can be imported. |
One signal alone is not a reason to leave. A three-line experiment that you will throw away belongs in the shell, even if you retype it once.
Moving a session into a file
Suppose you built a function through trial and error:
>>> def average(numbers):
... return sum(numbers) / len(numbers)
...
>>> average([1, 2, 3])
2.0
>>> average([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in average
ZeroDivisionError: division by zeroYou found a real edge case. Do not copy the history. Write the final version of the code, including the fix, into stats.py.
def average(numbers):
"""Return the mean of numbers, or None for an empty list."""
if not numbers:
return None
return sum(numbers) / len(numbers)
def main():
print(average([1, 2, 3]))
print(average([]))
if __name__ == "__main__":
main()Run it from the terminal:
python3 stats.pyThe output is:
2.0
NoneThe if __name__ == "__main__": guard matters. When you run python3 stats.py, Python sets __name__ to "__main__" and main() runs. When another file or your shell session does import stats, __name__ is "stats" and main() does not run. One file therefore works both as a script and as a module you can explore interactively.
Keeping the shell as a tool
Writing a file does not mean giving up the shell. The two work well together.
Load the file and then experiment on top of it:
python3 -i stats.pyThis runs main() through the guard, then leaves you at the prompt with average defined. You can try new inputs without writing a print statement for each. When an edit is needed, change the file, exit, and start again. Restarting takes a second, and it gives you a clean state each time.
For setup you want in every session, such as imports you always use, set the PYTHONSTARTUP environment variable to the path of a file. Python runs that file at the start of each interactive session. Keep it small. A startup file with a lot of logic recreates the hidden-state problem, because your session now depends on a file you have forgotten about.
Use importlib.reload() when restarting is expensive, for example when you have loaded a large dataset into memory. Call functions through the module name (mymodule.func()) so reloads take effect. Do not rely on it for classes with live instances.
Adding a check
Once the code is in a file, you can turn your shell experiments into assertions. Save this as test_stats.py:
from stats import average
def test_average_of_values():
assert average([1, 2, 3]) == 2.0
def test_average_of_empty_list():
assert average([]) is None
if __name__ == "__main__":
test_average_of_values()
test_average_of_empty_list()
print("all tests passed")Run it with python3 test_stats.py. The function names start with test_, so test runners such as pytest can also find them later. Each shell call you would have eyeballed is now a check that reports an error if the result changes.
A decision flow
Common mistakes when making the move
- Copying the prompts. Lines that start with
>>>or...are not Python source. Copy only the code. - Keeping lines that exist only to display values. In a file, a bare expression such as
average([1, 2, 3])computes the value but shows nothing. Useprint()to display it. - Leaving out setup that the session had. If your experiment relied on an earlier import or variable, add it to the file. Running from a fresh process exposes these gaps, which is a benefit.
- Naming the file after a standard module. A file called
math.pyorrandom.pyin your working directory can shadow the real module and cause strange import errors. - Running code at import time. Put work inside functions and call it from the
__main__guard, so importing the file does not trigger side effects.
Summary of the workflow
- Explore in the shell until you understand the behavior.
- Write the final code in a file, without prompts, with setup included.
- Run it from a fresh process with
python3 file.py. - Use
python3 -i file.pywhen you want to keep experimenting on top of it. - Turn the experiments you cared about into assertions.
Exercise
You define a function total_cost(items) in the shell. It works, and you save it into shop.py. When you run python3 shop.py, you get NameError: name 'TAX_RATE' is not defined, even though the function worked in the shell. What is the most likely cause, and how do you fix it?
Show answer
In the shell session you had earlier typed TAX_RATE = 0.2, so the global name existed when the function ran. The line was not copied into the file. Add TAX_RATE = 0.2 to shop.py above the function (or pass the rate as a parameter). Running from a fresh process exposes setup that the session was hiding.
Exercise
You edit mymodule.py to fix a bug in greet, then run importlib.reload(mymodule). Calling greet("Ada") still shows the old behavior, although you imported it with from mymodule import greet. Why, and what are two ways to get the new behavior?
Show answer
The name greet in your session still refers to the old function object, because reload re-runs the module but does not rebind names you imported with from ... import. You can call mymodule.greet("Ada") after the reload, or run from mymodule import greet again. Restarting the shell also works.
Exercise
Why does a script usually put its work in a main() function and call it under if __name__ == "__main__": instead of putting the statements at the top level of the file?
Show answer
When the file is imported, __name__ is the module name rather than "__main__", so the guarded call does not run. The same file can then be run as a script, imported by other code, or explored with python3 -i without unwanted side effects at import time.