changeset 2161:b2909ecf1fb3

fix TypeError
author drewp@bigasterisk.com
date Thu, 18 May 2023 11:53:32 -0700
parents 611c3e97de2f
children e69661cca1cb
files light9/collector/collector.py light9/newtypes.py
diffstat 2 files changed, 21 insertions(+), 11 deletions(-) [+]
line wrap: on
line diff
--- a/light9/collector/collector.py	Thu May 18 10:49:16 2023 -0700
+++ b/light9/collector/collector.py	Thu May 18 11:53:32 2023 -0700
@@ -10,7 +10,7 @@
 from light9.collector.weblisteners import WebListeners
 from light9.namespaces import L9, RDF
 from light9.newtypes import (ClientSessionType, ClientType, DeviceAttr, DeviceClass, DeviceUri, DmxIndex, DmxMessageIndex, OutputAttr, OutputRange, OutputUri,
-                             OutputValue, UnixTime)
+                             OutputValue, UnixTime, typedValue)
 
 log = logging.getLogger('collector')
 
@@ -19,15 +19,6 @@
     return DmxMessageIndex(base + offset - 1)
 
 
-ObjType = TypeVar('ObjType')
-
-
-def typedValue(objType: Type[ObjType], graph, subj, pred) -> ObjType:
-    obj = graph.value(subj, pred)
-    if obj is None:
-        raise ValueError()
-    conv = obj if issubclass(objType, URIRef) else obj.toPython()
-    return cast(objType, conv)
 
 
 def outputMap(graph: SyncedGraph, outputs: List[OutputInstance]) -> Dict[Tuple[DeviceUri, OutputAttr], Tuple[OutputInstance, DmxMessageIndex]]:
--- a/light9/newtypes.py	Thu May 18 10:49:16 2023 -0700
+++ b/light9/newtypes.py	Thu May 18 11:53:32 2023 -0700
@@ -1,5 +1,6 @@
-from typing import Tuple, NewType
+from typing import Tuple, NewType, Type, TypeVar, cast
 from rdflib import URIRef
+from rdflib.term import Node
 
 ClientType = NewType('ClientType', str)
 ClientSessionType = NewType('ClientSessionType', str)
@@ -19,3 +20,21 @@
 # Alternate output range for a device. Instead of outputting 0.0 to
 # 1.0, you can map that range into, say, 0.2 to 0.7
 OutputRange = NewType('OutputRange', Tuple[float, float])
+
+_ObjType = TypeVar('_ObjType')
+
+
+def _isSubclass2(t1: Type, t2: type) -> bool:
+    """same as issubclass but t1 can be a NewType"""
+    if hasattr(t1, '__supertype__'):
+        t1 = t1.__superType__
+    return issubclass(t1, t2)
+
+
+def typedValue(objType: Type[_ObjType], graph, subj, pred) -> _ObjType:
+    """graph.value(subj, pred) with a given return type. If objType is """
+    obj = graph.value(subj, pred)
+    if obj is None:
+        raise ValueError()
+    conv = obj if _isSubclass2(objType, Node) else obj.toPython()
+    return cast(objType, conv)
\ No newline at end of file