From 5a652f1710d976bdbff27068bf172a027af21a44 Mon Sep 17 00:00:00 2001 From: alemidev Date: Sat, 23 Apr 2022 14:33:30 +0200 Subject: [PATCH] try to parse Union hints --- src/treepuncher/treepuncher.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/treepuncher/treepuncher.py b/src/treepuncher/treepuncher.py index 9fd3961..a0f084b 100644 --- a/src/treepuncher/treepuncher.py +++ b/src/treepuncher/treepuncher.py @@ -6,7 +6,7 @@ import datetime import uuid import pkg_resources -from typing import List, Dict, Optional, Any, Type, get_args, get_origin, get_type_hints, Set, Callable +from typing import List, Dict, Optional, Union, Any, Type, get_args, get_origin, get_type_hints, Set, Callable from time import time from dataclasses import dataclass, MISSING, fields from configparser import ConfigParser @@ -36,6 +36,12 @@ def parse_with_hint(val:str, hint:Any) -> Any: return set(val.split()) if hint is dict or get_origin(hint) is dict: return json.loads(val) + if hint is Union or get_origin(hint) is Union: + for t in get_args(hint): + try: + return t(val) + except ValueError: + pass return (get_origin(hint) or hint)(val) # try to instantiate directly class ConfigObject: