Nicola Kluge NKluge at
Wed Jun 5 02:14:20 EDT 2002

Interesting approach.  However, once you do that.  The symbolic form of the
equations is lost.  For example,
>>> c=Eval()
>>> c.y='3'
>>> c.y
>>> c.a='4'
>>> c.a
>>> c.f='y*a'
>>> c.f

 >>> c.__dict__['dict']['f']

doesn't give you the equation back.

Your, approach goes under a lazy evaluation business.  However, I need to
have all dependent attributes which are nested deeper to be evaluated every
time.  That is why the equations should be retained in the  dictionary.  I
don't want to worry whether the previously evaluated attribute holds the
updated value or not.  Evaluations have to propagate all the way to the end,
for example in the above case, while evaluating c.f the evaluation should
evaluate 'y' so that we are sure that 'y' is still 3.  In you approach the
evaluation stops at 'f'=12 but it can't see whether 'y' changed even though
'f' once depended on 'y'.

Vojin Jovanovic

"Bjorn Pettersen" <BPettersen at> wrote in message
news:mailman.1023225848.26315.python-list at
> From: Vojin Jovanovic [mailto:vjovanov at]
> I don't see how that is going to work.  In fact I tried
> things like that before without success.  Just sticking the
> dictionary into eval/exec is missing the point.  Every time
> parsing is done flow needs to go through __getattr__ special
> method to evaluate nested equations.  Without self. you can't
> achieve that effect.  Try the approach you suggested and
> you'll get '#U'.

Perhaps something like this?

-- bjorn

class Eval:
    def __init__(self):
        self.__dict__['dict'] = {}
        exec "from math import *" in self.dict

    def __call__(self, expr):
            return eval(expr, self.dict, self.dict)
        except SyntaxError:
            exec expr in self.dict, self.dict

    def __getattr__(self, attr):
        return self.dict[attr]

    def __setattr__(self, attr, val):
        self.dict[attr] = eval(val, self.dict, self.dict)

e = Eval()

print e('pi * 3')
e('x = sin(0.5)')
print e.x
e.y = 'sin(0.5)'
print e.y

More information about the Python-list mailing list