2 ms·
But we don't want the string escaped. We want it interpreted.
by tedunangst 10y ago
But we don't want the string escaped. We want it interpreted.
- jgalt212 10y agoyes, basically eval is evil
- xapata 10y agoAnd yet, eval is necessary for so many important things...
- masklinn 10y agoThat's not even eval, the entire thing is a series of dynamic attribute lookups[0], you can trivially implement that in pure Python without needing to `eval` anything. [0] it also supports mapping and sequence lookups IIRC but that's about the same thing
- tzs 10y agoWe want it interpreted, but we don't have to let the language handle it directly. A much safer way is to define our own syntax for this and interpret it in our code, with that code only having access to a limited set of safe substitutions. For instance, suppose we want to allow user formatting of contact information. A contact entry has a name, address, phone number, and email address. The user supplies a template string using %_NAME_, %_ADDR_, %_PHONE_, and %_EMAIL where they would like the name, address, phone number, and email address substituted, respectively. I'd probably be doing this in Perl, and I'd do it something like this: sub format_contact { my($template, $name, $addr, $phone, $email) = @_; my %val = (name => $name, addr => $addr, phone => $phone, email => $email); $template =~ s/%_([a-z]+)_/$val{lc($1)}/gi; return $template; }