From bec1027a5246c4c808fc8aea7f07e1541476fba7 Mon Sep 17 00:00:00 2001 From: dnomd343 Date: Wed, 7 Sep 2022 14:52:52 +0800 Subject: [PATCH] update: add type utils --- Basis/Functions.py | 33 --------------------------------- Utils/Common/Type.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 33 deletions(-) create mode 100644 Utils/Common/Type.py diff --git a/Basis/Functions.py b/Basis/Functions.py index 61b763e..1c9ba6a 100644 --- a/Basis/Functions.py +++ b/Basis/Functions.py @@ -61,36 +61,3 @@ def genUUID() -> str: # generate uuid v5 )) -def toInt(raw) -> int: - try: - return int(raw) - except: - raise RuntimeError('Unable convert to int') - - -def toStr(raw) -> str: - if raw is None: - raise RuntimeError('None could not convert to str') - if isinstance(raw, bytes): # bytes -> str - return str(raw, encoding = 'utf-8') - try: - return str(raw) - except: - raise RuntimeError('Unable convert to str') - - -def toStrTidy(raw) -> str: - return toStr(raw).strip().lower() # with trim and lower - - -def toBool(raw) -> bool: - if isinstance(raw, (bool, int, float)): - return bool(raw) - try: - raw = toStr(raw).strip().lower() - if raw in ['true', 'false']: - return True if raw == 'true' else False - return int(raw) != 0 - except: - raise RuntimeError('Unable convert to bool') - diff --git a/Utils/Common/Type.py b/Utils/Common/Type.py new file mode 100644 index 0000000..69e4c96 --- /dev/null +++ b/Utils/Common/Type.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +def toInt(raw) -> int: + try: + return int(raw) + except: + raise RuntimeError('Unable convert to int') + + +def toStr(raw, allowNone: bool = False) -> str: + if raw is None: + if allowNone: # None => 'none' + return 'none' + raise RuntimeError('None could not convert to str') + if isinstance(raw, bytes): # bytes -> str + return str(raw, encoding = 'utf-8') + try: + return str(raw) + except: + raise RuntimeError('Unable convert to str') + + +def toStrTidy(raw, allowNone: bool = False) -> str: + return toStr(raw, allowNone).strip().lower() # with trim and lower + + +def toBool(raw) -> bool: + if isinstance(raw, (bool, int, float)): + return bool(raw) + try: + raw = toStr(raw).strip().lower() + if raw in ['true', 'false']: + return True if raw == 'true' else False + return int(raw) != 0 + except: + raise RuntimeError('Unable convert to bool')