evalstr

Alex Martelli aleaxit at yahoo.com
Thu Jul 12 09:40:17 EDT 2001


"Michael Chermside" <mcherm at destiny.com> wrote in message
news:mailman.994939340.22056.python-list at python.org...
> >>> class Eval:
> def __getitem__(self, key):
> return eval(key)
>
>
> >>> foo = 3.0
> >>> spam = 5.0
> >>> print "%(foo/spam)s" % Eval()
> 0.6
> >>> print "%(foo/spam).55f" % Eval()
> 0.5999999999999999800000000000000000000000000000000000000
> >>>
>
> 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.

How so...?

>>> class Eval:
...   def __getitem__(self,key): return eval(key)
...
>>> print "2+2 is %(2+2)s"%Eval()
2+2 is 4
>>> print "(2+2)*3 is %((2+2)*3)s"%Eval()
(2+2)*3 is 12
>>>


Alex






More information about the Python-list mailing list