improved subscribe
authorArmin Ronacher <armin.ronacher@active-4.com>
Tue, 13 May 2008 13:35:47 +0000 (15:35 +0200)
committerArmin Ronacher <armin.ronacher@active-4.com>
Tue, 13 May 2008 13:35:47 +0000 (15:35 +0200)
--HG--
branch : trunk

jinja2/compiler.py
jinja2/environment.py
jinja2/sandbox.py

index 4c250b5be742148b739ec5e597c5d984a1443063..6e05040c4f3e95c306fcfed7243da30662665afe 100644 (file)
@@ -1264,7 +1264,11 @@ class CodeGenerator(NodeVisitor):
         self.visit(node.expr, frame)
 
     def visit_Subscript(self, node, frame):
-        if isinstance(node.arg, nodes.Slice):
+        # slices or integer subscriptions bypass the subscribe
+        # method if we can determine that at compile time.
+        if isinstance(node.arg, nodes.Slice) or \
+           (isinstance(node.arg, nodes.Const) and
+            isinstance(node.arg.value, (int, long))):
             self.visit(node.node, frame)
             self.write('[')
             self.visit(node.arg, frame)
index 70fd3446c19060867aac6d02550a3ea87a4599db..d1206ef30615d4393c0444a1f4e8f011d109a334 100644 (file)
@@ -278,13 +278,15 @@ class Environment(object):
 
     def subscribe(self, obj, argument):
         """Get an item or attribute of an object."""
-        try:
-            return getattr(obj, str(argument))
-        except (AttributeError, UnicodeError):
+        if isinstance(argument, basestring):
             try:
-                return obj[argument]
-            except (TypeError, LookupError):
-                return self.undefined(obj=obj, name=argument)
+                return getattr(obj, str(argument))
+            except (AttributeError, UnicodeError):
+                pass
+        try:
+            return obj[argument]
+        except (TypeError, LookupError):
+            return self.undefined(obj=obj, name=argument)
 
     def parse(self, source, filename=None):
         """Parse the sourcecode and return the abstract syntax tree.  This
index 4b9ac13832a90035e3d033161c5501b054b0a488..c041a06d89edeb42d278dfdd0c54d7281ed5e6e7 100644 (file)
@@ -118,14 +118,15 @@ class SandboxedEnvironment(Environment):
     def subscribe(self, obj, argument):
         """Subscribe an object from sandboxed code."""
         is_unsafe = False
-        try:
-            value = getattr(obj, str(argument))
-        except (AttributeError, UnicodeError):
-            pass
-        else:
-            if self.is_safe_attribute(obj, argument, value):
-                return value
-            is_unsafe = True
+        if isinstance(argument, basestring):
+            try:
+                value = getattr(obj, str(argument))
+            except (AttributeError, UnicodeError):
+                pass
+            else:
+                if self.is_safe_attribute(obj, argument, value):
+                    return value
+                is_unsafe = True
         try:
             return obj[argument]
         except (TypeError, LookupError):