Mercurial > code > home > repos > light9
view light9/newtypes.py @ 2186:04612ba3fe45
refactor
author | drewp@bigasterisk.com |
---|---|
date | Fri, 19 May 2023 20:55:28 -0700 |
parents | 066f05ad7900 |
children | 9fc653ee7fff |
line wrap: on
line source
from typing import Tuple, NewType, Type, TypeVar, Union, cast from rdflib import URIRef from rdflib.term import Node ClientType = NewType('ClientType', str) ClientSessionType = NewType('ClientSessionType', str) Curve = NewType('Curve', URIRef) OutputUri = NewType('OutputUri', URIRef) # e.g. dmxA DeviceUri = NewType('DeviceUri', URIRef) # e.g. :aura2 DeviceClass = NewType('DeviceClass', URIRef) # e.g. :Aura DmxIndex = NewType('DmxIndex', int) # 1..512 DmxMessageIndex = NewType('DmxMessageIndex', int) # 0..511 DeviceAttr = NewType('DeviceAttr', URIRef) # e.g. :rx NoteUri = NewType('NoteUri', URIRef) OutputAttr = NewType('OutputAttr', URIRef) # e.g. :xFine OutputValue = NewType('OutputValue', int) # byte in dmx message Song = NewType('Song', URIRef) UnixTime = NewType('UnixTime', float) VT = TypeVar('VT', float, int, str) # remove HexColor = NewType('HexColor', str) VTUnion = Union[float, int, HexColor] # rename to ValueType DeviceSetting = Tuple[DeviceUri, DeviceAttr, # currently, floats and hex color strings VTUnion] # 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 not an rdflib.Node, we toPython() the value.""" obj = graph.value(subj, pred) if obj is None: raise ValueError() conv = obj if _isSubclass2(objType, Node) else obj.toPython() # may need to turn Decimal to float here return cast(objType, conv)