def type_to_dict(typ: type) -> TypeDict: """Convert a type into a dictionary representation that we can store. The dictionary must: 1. Be encodable as JSON 2. Contain enough information to let us reify the type """ if is_typed_dict(typ): return typed_dict_to_dict(typ) # Union and Any are special cases that aren't actually types. if is_union(typ): qualname = 'Union' elif is_any(typ): qualname = 'Any' elif is_generic(typ): qualname = qualname_of_generic(typ) else: qualname = typ.__qualname__ d: TypeDict = { 'module': typ.__module__, 'qualname': qualname, } elem_types = getattr(typ, '__args__', None) if elem_types and is_generic(typ): # empty typing.Tuple is weird; the spec says it should be Tuple[()], # which results in __args__ of `((),)` if elem_types == ((),): elem_types = () d['elem_types'] = [type_to_dict(t) for t in elem_types] return d
def test_is_typed_dict(self, typ, expected): assert is_typed_dict(typ) == expected