Question about using python as a scripting language

skip at pobox.com skip at pobox.com
Wed Aug 9 09:44:08 EDT 2006


    Wildemar> Heck, whenever *is* it OK to use eval() then?

When you're sure of the validity of the string you are feeding it.
Unfortunately, the more you know about the string (and thus how valid it is
in your current context), the less you need eval.  For example, if I know a
string s only contains digits and I want an integer out of the result, I can
avoid eval() by calling int(s).  Even if I don't know for sure that it's a
string of digits I'm still better off calling int() and trapping any
exceptions:

    try:
        n = int(s)
    except ValueError:
        print "hmmm...", repr(s), "doesn't look like an integer to me."

Skip



More information about the Python-list mailing list