Created
May 27, 2020 16:43
-
-
Save pirogoeth/04afae01b5ec577eece92086d593cab9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import typing | |
from functools import partial | |
from typing import Optional, Tuple, Type, Union | |
K = typing.TypeVar("K") | |
V = typing.TypeVar("V") | |
class TypedDict(typing.Dict[K, V]): | |
pass | |
def process_type(t: Type): | |
print(f"Got type {t}") | |
origin = typing.get_origin(t) | |
type_args = frozenset(typing.get_args(t)) | |
print(f"Origin {origin}") | |
origin_switch = { | |
Union: process_union, | |
None: partial(process_maybe_concrete, t), | |
} | |
return origin_switch.get(origin, process_unknown)(origin, type_args) | |
def process_union(origin: Type, args: Tuple[Type, ...]): | |
print(f" Union on {args}") | |
if type(None) in args: | |
options = args - {type(None)} | |
print(f" Type(s) {options} are Optional") | |
return | |
def process_unknown(origin: Type, args: Tuple[Type, ...]): | |
raise ValueError(f" Unhandled type: {origin}") | |
def process_maybe_concrete(actual: Type, _: Type, args: Tuple[Type, ...]): | |
print(" None origin") | |
# Maybe we can find out if this is a concrete type? | |
subclasses = { | |
typing.Dict: lambda o, a: print(" Is Dictish") | |
} | |
for subclass, fn in subclasses.items(): | |
if isinstance(actual, subclass): | |
fn(origin, args) | |
process_type(Optional[str]) | |
process_type(frozenset) | |
process_type(TypedDict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment