Commits

Anonymous committed ca37be1

support for self-referential properties

  • Participants
  • Parent commits 6e7cc14

Comments (0)

Files changed (1)

File ordf/vocab/owl.py

     >>> quebec.country = canada
     >>> for country in quebec.country: print [str(x) for x in country.label]
     ['Canada']
+
+    Try out some support for strings in place of class names for
+    self-referential classes.
+
+    >>> from ordf.namespace import FOAF
+    >>> class Person(Class):
+    ...     knows = object_predicate(FOAF.knows, "Person", globals())
+    ...
+    >>> bob = Person(EX.bob)
+    >>> alice = Person(EX.alice)
+    >>> bob.knows = alice
+    >>> [type(x) for x in bob.knows]
+    [<class '__main__.Person'>]
     """
-    def __init__(self, term, implementation=None):
+    def __init__(self, term, implementation=None, globals=None):
         if implementation is None:
-            implementation = Individual
-        assert issubclass(implementation, Individual), "expected an Individual, got an %s" % implementation
+            self._cls = Individual
+        if isinstance(implementation, basestring):
+            self._cls = implementation
+            self._globals = globals
+        else:
+            assert issubclass(implementation, Individual), "expected an Individual, got an %s" % implementation
+            self._cls = implementation
         super(object_predicate, self).__init__(term)
-        self._cls = implementation
+
     def _get(self, obj):
+        if isinstance(self._cls, basestring):
+            self._cls = self._globals[self._cls]
         for identifier in super(object_predicate, self)._get(obj):
             yield self._cls(identifier, graph=obj.graph)
 
     >>> for pet in bob.pet: print [str(x) for x in pet.label]
     ['Max']
     """
-    def __init__(self, term, implementation=None):
+    def __init__(self, term, implementation=None, globals=None):
         if implementation is None:
-            implementation = Individual
-        assert issubclass(implementation, Individual), "expected an Individual, got an %s" % implementation
+            self._cls = Individual
+        elif isinstance(implementation, basestring):
+            self._cls = implementation
+            self._globals = globals
+        else:
+            assert issubclass(implementation, Individual), "expected an Individual, got an %s" % implementation
+            self._cls = implementation
         super(cached_object_predicate, self).__init__(term)
-        self._cls = implementation
+
     def _set(self, obj, value):
         if not isinstance(value, list) and not isinstance(value, tuple):
             value = [value]
         _cache = self._cache(obj)
         if self.term in _cache: del _cache[self.term]
     def _get(self, obj):
+        if isinstance(self._cls, basestring):
+            self._cls = self._globals[self._cls]
         _cache = self._cache(obj)
         if self.term in _cache:
             return _cache[self.term]