The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)
Mark Lawrence
breamoreboy at yahoo.co.uk
Sun Mar 20 23:59:37 EDT 2016
On 21/03/2016 02:04, BartC wrote:
> On 21/03/2016 01:35, Chris Angelico wrote:
>> On Mon, Mar 21, 2016 at 12:28 PM, Mark Lawrence
>> <breamoreboy at yahoo.co.uk> wrote:
>>> I got to line 22, saw the bare except, and promptly gave up.
>>
>> Oh, keep going, Mark. It gets better.
>>
>> def readstrfile(file):
>> try:
>> data=open(file,"r").read()
>> except:
>> return 0
>> return data
>>
>> def start():
>> psource=readstrfile(infile)
>> if psource==0:
>> print ("Can't open file",infile)
>> exit(0)
>>
>>
>>
>> So, if any exception happens during the reading of the file, it gets
>> squashed, and 0 is returned - which results in a generic message being
>> printed, and the program terminating, with return value 0. Awesome!
>
> I don't have a clue about exceptions, but why wouldn't read errors be
> picked up by the same except: block?
If you don't understand exceptions, you don't understand Python, which
prefers EAFP than LBYL. See
https://docs.python.org/3/glossary.html#term-eafp and
https://docs.python.org/3/glossary.html#term-lbyl
>
> But I've anyway sprinkled one or two more try/excepts in there and put
> some actual exception codes in. However, this readstrfile() is just
> there to load the file into memory and avoid having a 200,000-line
> string in the program.
>
Just let the exception bubble up if anything goes wrong. In most
circumstances that's far better than masking everything that could
possibly go wrong.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Python-list
mailing list