evalstr
Carel Fellinger
cfelling at iae.nl
Thu Jul 12 10:37:46 EDT 2001
Michael Chermside <mcherm at destiny.com> wrote:
>>>> class Eval:
> def __getitem__(self, key):
> return eval(key)
...
> Now THAT'S a wierd-but-cool hack! Very powerful and flexible, and
> simple enough to use. It should definitely be added to the cookbook.
> It does, unfortunately, have one significant limitation: the expression
> cannot contain the character ")", which is one you'd like to use in
> expressions.
You can, but it has to match opening braces. The thing that is impossible
is to have strings inside the expression that have extra closing braces.
>>> "%((1+2)*(3+3))s" % Eval()
'18'
>>> "%('a'*2)s" % Eval()
'aa'
>>> "%('a)'*2)s" % Eval()
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __getitem__
File "<string>", line 1
'a
^
SyntaxError: invalid token
>>>
--
groetjes, carel
More information about the Python-list
mailing list