diff --git a/light9/collector/collector.py b/light9/collector/collector.py --- a/light9/collector/collector.py +++ b/light9/collector/collector.py @@ -10,7 +10,7 @@ from light9.collector.output import Outp 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 @@ def makeDmxMessageIndex(base: DmxIndex, 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]]: diff --git a/light9/newtypes.py b/light9/newtypes.py --- a/light9/newtypes.py +++ b/light9/newtypes.py @@ -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 @@ UnixTime = NewType('UnixTime', float) # 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