Source code for uw.scientia.uef_types

"""Cyon field value type definitions.
"""

from collections.abc import Set
import datetime
import re

__all__ = [
    'UEFHostKey',
    'UEFHostKeyNullable',
    'UEFText',
    'UEFTextNullable',
    'UEFDuration',
    'UEFMinuteTime',
    'UEFWeekDay',
    'UEFWeekPattern',
    'UEFSetOperator',
    'UEFBoolean',
    'UEFPositiveInteger',
    'UEFPreference',
]

class UEFType:
    def __init__ (self, value):
        if self.validate (value):
            self.__value = value
        else:
            raise ValueError ('Invalid value for UEF type %s: %s' % (type (self).__name__, value))

    @property
    def value (self):
        return self.__value

class UEFRETextType (UEFType):
    def __init__ (self, value):
        super ().__init__ ('' if value is None else value)

    def validate (self, value):
        return isinstance (value, str) and self.re.fullmatch (value) is not None

    def format (self):
        return self.value

[docs]class UEFHostKey (UEFRETextType): re = re.compile ('[^\n\t]+')
[docs]class UEFHostKeyNullable (UEFRETextType): re = re.compile ('[^\n\t]*')
[docs]class UEFText (UEFRETextType): re = re.compile ('[^\n\t]+')
[docs]class UEFTextNullable (UEFRETextType): re = re.compile ('[^\n\t]*')
[docs]class UEFDuration (UEFType):
[docs] def validate (self, value): return isinstance (value, datetime.timedelta) and value.total_seconds () % 60 == 0
[docs] def format (self): return str (int (self.value.total_seconds ()) // 60)
[docs]class UEFMinuteTime (UEFType):
[docs] def validate (self, value): return isinstance (value, datetime.time) and (value == datetime.time.max or value.second == value.microsecond == 0)
[docs] def format (self): if self.value == datetime.time.max: return str (24 * 60) else: return str (self.value.hour * 60 + self.value.minute)
[docs]class UEFWeekDay (UEFType):
[docs] def validate (self, value): return isinstance (value, int) and 0 <= value < 7
[docs] def format (self): return str (self.value)
[docs]class UEFWeekPattern (UEFType): WEEKS_IN_YEAR = 52 __allowed = frozenset (range (WEEKS_IN_YEAR))
[docs] def validate (self, value): return isinstance (value, Set) and not (value - self.__allowed)
[docs] def format (self): return ''.join (str (int (i in self.value)) for i in range (self.WEEKS_IN_YEAR))
[docs]class UEFSetOperator (UEFRETextType): re = re.compile ('[-+](all)?')
[docs]class UEFBoolean (UEFType):
[docs] def validate (self, value): return isinstance (value, bool)
[docs] def format (self): return str (int (self.value))
[docs]class UEFPositiveInteger (UEFType):
[docs] def validate (self, value): return isinstance (value, int) and value >= 0
[docs] def format (self): return str (self.value)
[docs]class UEFPreference (UEFType):
[docs] def validate (self, value): return isinstance (value, int) and -10 <= value <= 10
[docs] def format (self): return str (self.value)