NumberDef: Bind random and builtins in a separate dictionary. Replace $rand with...
authorJoe Wreschnig <joe.wreschnig@gmail.com>
Wed, 17 Mar 2010 02:44:09 +0000 (19:44 -0700)
committerJoe Wreschnig <joe.wreschnig@gmail.com>
Wed, 17 Mar 2010 02:44:09 +0000 (19:44 -0700)
bulletml/expr.py

index 33f7d44bf1af0ba57be9955ec30b461a8c6064c3..7654fed4b6c10a7c37b998f1e6fb6d00b3525be7 100644 (file)
@@ -29,6 +29,8 @@ class NumberDef(object):
     (2+$1)*0.3
 
     """
+
+    GLOBALS = dict(random=random.random, __builtins__={})
     def __init__(self, expr):
         try:
             expr = expr.__original
@@ -37,14 +39,13 @@ class NumberDef(object):
         self.__original = expr
         repl = lambda match: "params[%d]" % (int(match.group()[1:]) - 1)
         expr = re.sub(r"\$\d+", repl, expr.lower())
-        self.__expr = expr.replace("$rand", "rand").replace("$rank", "rank")
+        self.__expr = expr.replace("$rand", "random()").replace("$rank", "rank")
         try:
             try:
                 self.__value = eval(self.__expr, dict(__builtins__={}))
             except NameError:
-                fake = [0] * 99
-                variables = dict(rand=1, rank=1, params=fake, __builtins__={})
-                value = eval(self.__expr, variables)
+                variables = dict(rank=1, params=[0] * 99)
+                value = eval(self.__expr, self.GLOBALS, variables)
                 if not isinstance(value, (int, float)):
                     raise TypeError(expr)
                 self.__value = None
@@ -56,9 +57,8 @@ class NumberDef(object):
         """Evaluate the expression and return its value."""
         if self.__value is not None:
             return self.__value
-        rand = random.random()
-        variables = { 'rand': rand, 'rank': rank, 'params': params }
-        return eval(self.__expr, variables)
+        variables = { 'rank': rank, 'params': params }
+        return eval(self.__expr, self.GLOBALS, variables)
 
     def __repr__(self):
         return "%s(%r)" % (type(self).__name__, self.__original)