<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Tue, Nov 7, 2017 at 6:41 AM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve@pearwood.info" target="_blank">steve@pearwood.info</a>></span> wrote:<br><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class="">> >Also, it is unfortunate that `ast.literal_eval` is less accessible than<br>
> >`builtins.eval`. Giving it an alias in builtins might make it easier for<br>
> >programmers (and less scary - "ast" might sound like I need a PhD to use<br>
> >it).<br></span></blockquote><div><br></div><div>I agree -- literal_eval is a really nice utility, but folks are not likely to find it...or think it's as simple a tool as it is...</div><div><br></div><div>In fact, a couple weeks ago, one of the students in my intro to python class used it -- good for him!), When my TA was reviewing the code (and she's a pretty experienced developer), she asked me:</div><div><br></div><div>what is the ast module?</div><div><br></div><div>I know it's the "Abstract Syntax Tree" module, so was very surprised that an intro student was messing about the the AST!</div><div><br></div><div>when I looked at the code, I saw, oh that's literal_eval -- a simple (seeming, anyway) function that a beginner may just want to use (good old stack overflow...)</div><div><br></div><div>I can see why liter_eval is needed in the AST module, but it's also a useful tool by itself,a nd that seems like a very strange place to store it...</div><div><br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">In any case, I think that securing literal_eval is much simpler than<br>
securing eval:<br>
<br>
try:<br>
# a thousand character expression ought to be enough for<br>
# any legitimate purpose...<br>
value = literal_eval(tainted_string[:<wbr>1000]) # untested<br>
except MemoryError:<br>
value = None<br></blockquote><div><br></div><div>sure -- though I'd use a lot more than 1000 characters -- not much these days, and you might want to unpack something like a JSON data package...</div><div><br></div><div>And I'd raise an exception if it's too big, rather than trying to evaluate the subset...</div><div><br></div><div>Maybe something like this should be patched into it?</div><div><br></div><div>-CHB</div></div><br clear="all"><div><br></div>-- <br><div class="gmail_signature" data-smartmail="gmail_signature"><br>Christopher Barker, Ph.D.<br>Oceanographer<br><br>Emergency Response Division<br>NOAA/NOS/OR&R (206) 526-6959 voice<br>7600 Sand Point Way NE (206) 526-6329 fax<br>Seattle, WA 98115 (206) 526-6317 main reception<br><br><a href="mailto:Chris.Barker@noaa.gov" target="_blank">Chris.Barker@noaa.gov</a></div>
</div></div>