open() and EOFError

Dan Stromberg drsalists at gmail.com
Mon Jul 7 18:07:43 CEST 2014


On 7/7/14, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> On 07/07/2014 09:09, Chris Angelico wrote:
>> On Mon, Jul 7, 2014 at 6:00 PM, Steven D'Aprano <steve at pearwood.info>
>> wrote:
>>> How do people feel about code like this?
>>>
>>> try:
>>>      name = input("Enter file name, or Ctrl-D to exit")
>>>      # On Windows, use Ctrl-Z [enter] instead.
>>>      fp = open(name)
>>> except EOFError:
>>>      sys.exit()
>>> except IOError:
>>>      handle_bad_file(name)
>>> else:
>>>      handle_good_file(fp)
>>
>> It seems trivial in this example to break it into two try blocks:
>>
>> try:
>>      name = input("Enter file name, or Ctrl-D to exit")
>>      # On Windows, use Ctrl-Z [enter] instead.
>> except EOFError:
>>      sys.exit()
>> try:
>>      fp = open(name)
>> except IOError:
>>      handle_bad_file(name)
>> else:
>>      handle_good_file(fp)
>>
>
> All those extra lines to type, not on your life.  Surely it would be
> better written as a one liner?

Don't be afraid of a few extra keystrokes.  Clarity is king.



More information about the Python-list mailing list