Skip to content

Instantly share code, notes, and snippets.

@pirogoeth
Created May 27, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirogoeth/04afae01b5ec577eece92086d593cab9 to your computer and use it in GitHub Desktop.
Save pirogoeth/04afae01b5ec577eece92086d593cab9 to your computer and use it in GitHub Desktop.
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