Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #41255 > unrolled thread
| Started by | Ken Seehart <ken@seehart.com> |
|---|---|
| First post | 2013-03-14 20:02 -0700 |
| Last post | 2013-03-14 20:02 -0700 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Yet another attempt at a safe eval() call Ken Seehart <ken@seehart.com> - 2013-03-14 20:02 -0700
| From | Ken Seehart <ken@seehart.com> |
|---|---|
| Date | 2013-03-14 20:02 -0700 |
| Subject | Re: Yet another attempt at a safe eval() call |
| Message-ID | <mailman.3329.1363316529.2939.python-list@python.org> |
[Multipart message — attachments visible in raw view] — view raw
On 1/4/2013 5:33 AM, Steven D'Aprano wrote:
> On Fri, 04 Jan 2013 07:24:04 -0500, Terry Reedy wrote:
>
>> On 1/3/2013 6:25 PM, Grant Edwards wrote:
>>> I've written a small assembler in Python 2.[67], and it needs to
>>> evaluate integer-valued arithmetic expressions in the context of a
>>> symbol table that defines integer values for a set of names. The
>>> "right" thing is probably an expression parser/evaluator using ast, but
>>> it looked like that would take more code that the rest of the assembler
>>> combined, and I've got other higher-priority tasks to get back to.
>> Will ast.literal_eval do what you want?
> No. Grant needs to support variables, not just literal constants, hence
> the symbol table.
>
>
Apologies for the delayed response...
Seems like it would be a bit safer and easier to approach this problem
by stretching the capability of ast.literal_eval() rather than
attempting to sandbox eval().
How about ast.literal_eval after performing lexical substitution using
the symbol table?
Assignment into the symbol table, and error handling, are exercises left
to the reader.
Something vaguely like this:
/pseudocode:/
def safe_eval(s, symbols={}):
while search(s, r'\w+'):
replace match with '('+repr(symbols[match])+')' in s
return ast.literal_eval(s)
- Ken
Back to top | Article view | comp.lang.python
csiph-web