MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
MCS 275 uses notebooks for homework, worksheets, and project descriptions, so you've seen these before. But you usually see a version converted to HTML.
Most users can install Jupyter using pip:
python3 -m pip install notebook
Then run the interface with:
python3 -m notebook
Of course, you need to replace python3
with your interpreter name.
A few of the many keyboard shortcuts:
You see the whole notebook, but the Python interpreter only sees code cells you run.
Output from cells can be saved with the notebook, making it hard to tell which cells have been executed.
Jupyter server program keeps running until you stop it (closing browser does not do that).
Text cells (Colab) or markdown cells (Jupyter) contain formatted text. When editing, formatting is specified with a language called Markdown.
# Heading level 1
## Heading level 2
### Heading level 3
* Bullet list item
* Another **excellent** item
1. *Numbered* list item
1. Another numbered list item
You can also do math: $\int_0^\infty e^{-x^2} \, dx$
Links: [text to display](https://example.com)
Will this function always close the file?
def file_contains_walrus(fn):
"""Return True if "walrus" is a line of file `fn`"""
fileobj = open(fn,"r",encoding="UTF-8")
for line in fileobj:
if line.strip() == "walrus":
fileobj.close()
return True
return False
Currently, in CPython (the usual interpreter): Yes.
In CPython, local variables are deleted as soon as a function returns. Deleting a file object closes the file.
But this isn't a language guarantee!
Possible bug: something might prevent step 3 from being reached (e.g. exception or return in step 2). Resource may not be released at all.
Use with
block to ensure automatic file closing.
with open("data.txt","w",encoding="UTF-8") as fileobj:
fileobj.write(...)
fileobj.write(...)
# other write operations...
print("At this point, the file is already closed")
Extra bonus: you can see exactly what part of the program needs the open file.
A file opened using a with
block will be closed as soon as execution flow leaves the block
even if it does so due to an exception or return.
Always open files using with
, and make the body as short as possible.
Think of files like refrigerators: Open only if needed, and for the shortest time possible.
The with
statement is not just for files; it can be used for any acquire-use-release situation.
Any class that is a context manager can be used after with
in the same way as open()
.
A context manager is a class with special methods:
__enter__
to perform setup__exit__
to perform cleanupContext managers are appropriate for:
__enter__(self):
as
in with
statement.__exit__(self,exc_type,exc,tb):
with
block.Expect each method to be called exactly once.
Some examples (listed as class - resource)
open
- Open filethreading.Lock
- Thread-exclusive righturllib.request.urlopen
- HTTP connectiontempfile.TemporaryFile
- Temporary file (deleted after use)