On 21/03/2016 02:02, Mark Lawrence wrote:
On 21/03/2016 01:35, Chris Angelico wrote:
On Mon, Mar 21, 2016 at 12:28 PM, Mark Lawrence
<breamore...@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!

ChrisA


The essential question is "which is faster?".  Who cares about trivial
little details like the user being given false data, as (say) they can
open the file but can't read it.  Or inadvertantly writing an infinite
loop and not being able to CTRL-C out of it, having to revert to your OS
to kill the rogue that's killing your CPU.

25 years of trying to teach people how to write Pythonic code and this
is how far we've got.  Heck, I think I'll see my GP later today for some
more, more powerful, tranquilisers.


This code was adapted from a program that used:

   readstrfile(filename)

which either returned the contents of the file as a string, or 0.

That's all. My Python version was thrown together as I don't know if there's a similar function to do the same.

If you want to talk about Pythonic, I don't see why that file API doesn't count (the original is buried in a library).

Or does Pythonic mean bristling with exceptions and classes and what-not?


--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to