[Tutor] Using a dictionary to map functions

Colby Christensen colbychristensen at hotmail.com
Tue Apr 26 10:44:54 EDT 2016


Thank you for your input. You have given me some more to consider.

> Date: Tue, 26 Apr 2016 22:17:53 +1000
> From: steve at pearwood.info
> To: tutor at python.org
> Subject: Re: [Tutor] Using a dictionary to map functions
> 
> Hi Colby, and welcome!
> 
> On Tue, Apr 26, 2016 at 12:30:38AM -0400, Colby Christensen wrote:
> 
> > try:
> >     infile = open(raw_input("Enter input file name; name.txt:"),'r')
> > except:
> >     print "Invalid filename"
> >     exit()
> 
> I'm afraid that code is misleading: your error message lies.
> 
> It may not be an "invalid filename". It could be any of the following:
> 
> - an invalid file name (a file name prohibited by the operating system); 
> - a valid file name that just doesn't exist; 
> - a valid file name that you don't have permission to access;
> - a valid file name that you can access, but a disk error occurred;
> - a valid file name on a network drive, but a network error occurred; 
> 
> and probably more. There are few things more frustrating than dealing 
> with programs that lie to you:
> 
>     "What do you mean, invalid filename? The file is right there, I 
>     can see it! How can this stupid program not find it? I've tried
>     a dozen times, double and triple checked that the file name is
>     correct, and it still says the file is invalid."
> 
> Because the real error is *permission denied*, not invalid file name.
> 
> Python spends a lot of effort to give detailed and useful error messages 
> when an error occurs. For example, if you try to open a file that 
> doesn't exist, Python reports:
> 
> IOError: [Errno 2] No such file or directory
> 
> and tells you the name of the file that you tried to open. If you don't 
> have permission to access it, it reports:
> 
> IOError: [Errno 13] Permission denied
> 
> and again reports exactly what went wrong.
> 
> Python provides you with a detailed error message telling you exactly 
> what went wrong, and you throw that away, replacing it with a generic 
> message which will be wrong more often than right. Please don't do that 
> -- trust me, you will come to regret it.
> 
> In this case, the right way to deal with errors opening the file is... 
> not to deal with them at all. Instead of this:
> 
> try:
>     infile = open(raw_input("Enter input file name; name.txt:"),'r')
> except:
>     print "Invalid filename"
>     exit()
> 
> just write this:
> 
> infile = open(raw_input("Enter input file name; name.txt:"),'r')
> 
> (There are alternatives that are even better, but you probably haven't 
> learned about them yet.)
> 
> 
> 
> -- 
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
 		 	   		  


More information about the Tutor mailing list