On 9 February 2014 13:28, Russel Winder <rus...@winder.org.uk> wrote:
> On Mon, 2014-01-20 at 10:41 +0000, Oscar Benjamin wrote:
> [...]
>> f = open('myfile.txt')
>> for line in f:
>>     print(line.upper())
>> f.close()
>
> I suggest we even see this as not good code due to the possibility of
> I/O exceptions:
>
>         with open('myfile.txt') as f:
>             for line in f:
>                 print(line.upper())
>
> should, I argue, be the canonical idiom in modern Python.

I agree entirely, but what you've overlooked is that my examples are
carefully targeted at a particular part of a tutorial-based class.
We're talking about iteration so this is quite early in the course. At
this stage I want my students to understand that closing a file is an
explicit action that needs to occur. Later in the course I will teach
exception handling and explain that the above should be rewritten as

f = open('myfile.txt')
try:
    for line in f:
        print(line.upper())
finally:
    f.close()

Shortly after that we will look at using (but not creating) context
managers and I'll explain that file objects are also context managers.


Oscar
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to