Skip to content

Instantly share code, notes, and snippets.

@kirankotari
Last active January 11, 2022 00:28
Show Gist options
  • Save kirankotari/3ac6b9e05e13db86dbf82d5aefde13ca to your computer and use it in GitHub Desktop.
Save kirankotari/3ac6b9e05e13db86dbf82d5aefde13ca to your computer and use it in GitHub Desktop.
python input typecasting for major data types
from distutils import util
def _msg(args, msg=None):
msg = "input value error, please check your inputs." if msg is None else msg
return (f"{msg} {args[-1]}",)
def _try(func):
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except ValueError as e:
e.args = _msg(e.args)
raise(e)
except Exception as e:
raise(e)
return wrap
@_try
def inner(ip, typecaste, delimiter=None):
if type(ip) == str:
ip = list(map(typecaste, ip.split(delimiter)))
# ip = [typecaste(i) for i in ip.split(delimiter)]
return ip if len(ip) > 1 else ip[-1]
def _int(ip, delimiter=" "):
return inner(ip, int, delimiter)
def _float(ip, delimiter=" "):
return inner(ip, float, delimiter)
def _str(ip, delimiter=" "):
return inner(ip, str, delimiter)
def _bool(ip, delimiter=" "):
return inner(ip, lambda x: bool(util.strtobool(x)), delimiter)
def _complex(ip, delimiter=" "):
# TODO: delimiter issue on ip = "2 + 1j"
return inner(ip, complex, delimiter)
def mix(v):
precidence=float if '.' in v else int
try:
return float(v) if precidence is float else int(v)
except ValueError:
# TODO: can contains bool and complex
return str(v)
def _mix(ip, delimiter=" "):
return inner(ip, mix, delimiter)
@kirankotari
Copy link
Author

kirankotari commented Jan 11, 2022

ignoring the list, dict and tuple, we don't derive from string like "[1, 2, 3]" from input() or sys.stdin.readline()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment