self

Bjorn Pettersen BPettersen at NAREX.com
Tue Jun 4 17:09:07 EDT 2002


> From: Vojin Jovanovic [mailto:vjovanov at stevens-tech.edu] 
> 
> 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):
        try:
            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