was: Take 2: PEP draft for expression embedding

Steven Majewski sdm7g at Virginia.EDU
Wed Dec 19 20:22:42 EST 2001


Ok: how about something like this (using 2.2 -- the same thing
is possible with earlier versions, but defined slighly differently):

>>> class D(dict):
...     def __init__( self, d ):
...             self.d = d
...     def __getitem__(self, key ):
...             try:
...                     return self.d[key]
...             except KeyError:
...                     return eval(key, self.d)
...


I'm just pasting this from a python session: the class needs a descriptive
name:  class EvaluatingDict ?

>>> e = D(locals())
>>> e['sin']
<built-in function sin>
>>> e['x']
0.5
>>> e['sin(x)']
0.47942553860420301

Got the idea ?
Now use that evaluating dict with a format string:

>>> "X=%(x)s, sin(x)=%(sin(x))s" % e
'X=0.5, sin(x)=0.479425538604'


-- Steve









More information about the Python-list mailing list