[Tutor] Security [Was: Re: Decoding]

wesley chun wescpy at gmail.com
Tue Aug 14 03:30:31 CEST 2007


> > The original poster posted a post with the following function:
> >         def dec():
> >             import string
> >             message=raw_input("Enter the message to decode: ")
> >             result=''
> >             for x in string.split(message):
> >                 result=result+chr(eval(x))
> >             return result
> >
> >         print dec()


i echo everyone else's sentiments on the use of eval(), esp. in this
example.  it seems like it was created in the old Python 1.x days.  a
useful exercise for everyone here is to figure out what this piece of
code is supposed to do, and refactor it so that it's safer and easier
to understand.  my suggestions would include:

- remove reference to the string module and just use (string) methods
- remove eval()
- put together the string without using concatenation

something like this would be better:
result = ''.join([chr(x) for x in message.split()])

also, i think that user interaction should be kept out of "calculation
functions." by that i mean that you can have code that does
raw_input() and print, but the core functionality should just take
input, say 'message' and return an object, all without user
interaction.  that way, you can reuse your code more easily in other
applications where you desire this functionality.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list