srtring to int question

Bernhard Herzog herzog at online.de
Sun Aug 13 15:49:29 EDT 2000


"Darrell Gallion" <darrell at dorb.com> writes:

> "Bernhard Herzog"  wrote:
> > Using assert for this is a bad idea. Assert statements will be omitted
> > if the code is optimized (Python's -O option). They're meant to check
> > internal program state and invariants, not to validate user input.
> >
> Your right.
> 
> import re, sys
> globalNames={'hex':__builtins__.hex, 'int':__builtins__.int,
> 'raw_input':__builtins__.raw_input}

Putting these into globalNames is not really necessary because exec and
eval will add the __builtin__ module to the dict passed in as the
globals dict anyway, unless there is already a __builtins__ entry in the
dict. That's how resticted execution works, btw, by having a custom
__builtins__ dictionary in the globals dict.

> def convert(s):
>     try:
>         exec(s,globalNames, globalNames)
>         return globalNames.get("x",None)
>     except:
>         import traceback
>         traceback.print_exc ()
> 
> def convert1(s):
>     if re.match("(\s*[-+*\\=]?\s*\d+\.?\d*\s*)+",s):
>         try:
>             return eval(s,globalNames, globalNames)
>         except:
>             import traceback
>             traceback.print_exc ()
> 
> 
> > The regex used has a bug, btw. It doesn't allow signs, e.g. "-1" will
> > not be matched.
> >
> Not a bug, since Julian dates can't be negative. These instant code examples
> are nice distractions from the hard problems I supposed to be working on :)

Yes, I realized that from Alex Martelli's reply. It still has different
bug, though. Both the new regex and the old also match the string

   "10, __import__('os').system('ls /')"

or the more harmless "10," which doesn't evaluate to a number. Appending
a "$" to the end of the regexes should help.

-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list