[Tutor] Is my style OK in this elementary student exercise?

Rich Lovely roadierich at googlemail.com
Sat Jul 4 19:10:36 CEST 2009


2009/7/4 Angus Rodgers <angusr at bigfoot.com>:
>
> Fear not, I won't post all my exercises to the Tutor list!  But
> when I seem to be doing something a little elaborate, it seems a
> good idea to ask if I'm doing anything silly.  In this exercise:
>
> <http://python.pastebin.com/d7e245e0f>   (retention: 1 day)
>
> my /conscious/ worries are:
>
>  (i) trapping the exception StandardError may, for all I know,
> be a daft thing to do;
>
>  (ii) I'm not bothering to be consistent in my use of single and
> double string quotes (but I don't know how much difference this
> makes, to readability and/or reliability);
>
> (iii) some of my lines of code extend beyond 79 characters (but
> again, I don't know how much this matters);
>
>  (iv) correlatively with (iii), my indentation perhaps looks a
> little extreme (perhaps suggesting a redesign, I don't know);
>
>  (v) I'm bound to be doing other silly things that I don't even
> know about ("unknown unknowns").
>
> Any comments? (I don't expect the Spanish Inquisition!)
>
> --
> Angus Rodgers
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Lets consider how you handle your input.

You get a string, from the user, then you pass it to eval, which runs
it as if it was a python command.  Consider if they put in something
like the following:
__import__('os').system("rm -rf /")

If you know linux, you will know this is a bad thing.  A similar idea
on windows is __import__('os').system("format c: /q")

In short, unless you really know what you're doing, never use
eval(raw_input(...)) for the same reasons you should never use
input(...), for in effect, that is exactly what you are using.

In fact, the python 3.0 docs recommend that form (using the new name
for raw_input), in expert scripts allowing interactive code entry.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com


More information about the Tutor mailing list