Using Python for date calculations

Chris Angelico rosuav at
Fri Nov 21 15:08:07 CET 2014

On Sat, Nov 22, 2014 at 12:58 AM,  <random832 at> wrote:
> On Fri, Nov 21, 2014, at 05:47, Chris Angelico wrote:
>> Now, maybe you want it to eval. There are times when I conceptually
>> want "enter an integer", but it makes good sense to be able to type
>> "1+2" and have it act as if I typed "3". That's fine... but if you
>> want eval, write eval into your code. Be explicit:
>> eval(raw_input("Enter a number: ")) makes it very clear that you're
>> accepting code at the console.
> Out of curiosity, is there a way to use eval "safely" (i.e. strictly
> limiting what it has access to) across a privilege boundary? This also
> comes up for pickle and other serialization formats that can store
> arbitrary classes (i.e. call arbitrary constructors).

No, there is not. Not in Python. You can sandbox the entire process,
but you can't eval less-privileged code in a more-privileged process,

> I remember an IRC channel I sometimes go in has a chatbot (written in
> perl) which has a calculator function, it goes with the low-tech
> solution of removing via regex anything that isn't an operator or a
> number literal.

Would ast.literal_eval work? If not, it would at least be possible to
do an AST parse, then walk the tree and see if there's anything that
isn't an acceptable node type. There'd have to be draconian rules (no
attribute access, for instance), but it could be done more
intelligently than regex.


More information about the Python-list mailing list