1

this is my code, I want to use eval() to get the rule status but eval() needs local variables, there is many classes that inherits the base class, so I need to rewrite get_stat() in every class.

I want to avoid this, an idea is to create dynamic variables in get_stat(),eg. class b dynamically creates variables a and b in func get_stat()

How should I create dynamic varables in function? or any other way to avoid this stupid idea. I use python 3.2.3, locals() does not work

class base(object):
    def check(self):
        stat = get_stat()
    def get_stat(self):
        pass

class b(base):
    rule = 'a > 5 and b < 3'
    a = 0
    b = 0

    def update_data(self, a, b):
        self.a = a
        self.b = b

    def get_stat(self):
        a = self.a
        b = self.b
        return eval(rule)

class b(base):
    rule = 'd > 5 and e < 3'
    d = 0
    e = 0

    def update_data(self, d, e):
        self.d = d
        self.e = e

    def get_stat(self):
        d = self.d
        e = self.e
        return eval(rule)
2
  • i don't see what's dynamic here! You're still re-writing rule for every class, you might as well just re-write the function Commented Nov 20, 2012 at 11:15
  • @vikki: I suppose it's dynamic in the sense that the rule attribute of each subclass can be changed on-the-fly and get_stat() will return results based on it's current value. You're right about the fact that rule could just as well be made a method, although the syntax needed to change it might not be as convenient or clean looking as would be this way. Commented Nov 20, 2012 at 15:09

1 Answer 1

2

You can pass a dictionary to the eval() function containing the variables to evaluate the expression against:

>>> eval("a + b", {"a": 2, "b": 3})
5

Pass self.__dict__ to give access to an object's attributes:

>>> class MyClass(object):
...     def __init__(self):
...             self.a = 2
...             self.b = 3
... 
>>> obj = MyClass()
>>> obj.__dict__
{'a': 2, 'b': 3}
>>> eval("a + b", obj.__dict__)
5

Links:

Sign up to request clarification or add additional context in comments.

2 Comments

I think to be crystal clear you should state that they could use return eval(rule, self.__dict__) or return eval(rule, vars(self)).
Probably store these in an attribute, like self.variables = {"a": 2, "b": 3} and then the code can simply be eval(rule, self.variables)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.