Commits

Brian Beck  committed 74c57bc

Created VariableExpression class to allow v.x[p:o] shortcut (instead of subject(v.x)[p:o]).

  • Participants
  • Parent commits 53943f1

Comments (0)

Files changed (3)

File examples/ptrec.py

     offset = int(surg_seq) - 1
 
     query = Select([v.event, v.start_min, v.start_max]).where(
-        subject(v.event)[is_a: PTREC.Event_management_operation,
-                         DNODE.contains: v.start],
-        subject(v.start)[is_a: PTREC.EventStartDate,
-                         PTREC.hasDateTimeMin: v.start_min,
-                         PTREC.hasDateTimeMax: v.start_max]
+        v.event[is_a: PTREC.Event_management_operation,
+                DNODE.contains: v.start],
+        v.start[is_a: PTREC.EventStartDate,
+                PTREC.hasDateTimeMin: v.start_min,
+                PTREC.hasDateTimeMax: v.start_max]
     ).filter(
         v.start_min >= surg_min, v.start_max < surg_max
     ).order_by(v.start_min).limit(1).offset(offset)

File lib/telescope/sparql/expressions.py

 def or_(*operands):
     return ConditionalExpression(operator.or_, operands)
 
-class VariableExpressionConstructor(object):
+class VariableExpression(Expression):
     _VARIABLES = weakref.WeakValueDictionary()
     
-    def __call__(self, name):
+    def __new__(cls, name):
         if isinstance(name, basestring):
             name = unicode(name)
+            try:
+                instance = cls._VARIABLES[name]
+            except KeyError:
+                instance = super(VariableExpression, cls).__new__(cls, name)
+                instance._initialized = False
+                cls._VARIABLES[name] = instance
+            return instance
         else:
             raise TypeError("Variable names must be strings.")
-        try:
-            expr = self._VARIABLES[name]
-        except KeyError:
-            expr = self._VARIABLES[name] = Expression(Variable(name))
-        return expr
+    
+    def __init__(self, name):
+        if not self._initialized:
+            super(VariableExpression, self).__init__(Variable(name))
+            self._initialized = True
+    
+    def __getitem__(self, predicate_object_list):
+        from telescope.sparql.patterns import TriplesSameSubject
+        return TriplesSameSubject(self)[predicate_object_list]
+
+class VariableExpressionConstructor(object):
+    def __call__(self, name):
+        return VariableExpression(name)
     
     def __getattr__(self, name):
         return self(name)

File lib/telescope/sparql/patterns.py

 import warnings
-from telescope.sparql.expressions import Expression, and_
+from telescope.sparql.expressions import and_
 
 __all__ = ['Triple', 'TriplesSameSubject', 'Filter', 'GraphPattern',
            'GroupGraphPattern', 'UnionGraphPattern', 'union', 'optional']