Skip to content

Instantly share code, notes, and snippets.

@erickpeirson
Created April 26, 2019 13:23
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 erickpeirson/8fbc1afa6058494d53ead446cbac015b to your computer and use it in GitHub Desktop.
Save erickpeirson/8fbc1afa6058494d53ead446cbac015b to your computer and use it in GitHub Desktop.
class APIv4(API):
"""JSON Schema draft 4."""
...
def object(self, ctx: AnalyzeTypeContext, schema: Dict[str, Any],
outer: bool = False, **kwargs) -> Type:
"""Generate an annotation for an object, usually a TypedDict."""
properties = schema.get('properties')
if properties is None:
return named_builtin_type(ctx, 'dict')
try:
fallback = ctx.api.named_type('mypy_extensions._TypedDict', [])
except AssertionError:
fallback = named_builtin_type(ctx, 'dict', [])
items, types = zip(*filter(lambda o: o[1] is not None, [
(prop, self.get_type(ctx, subschema))
for prop, subschema in properties.items()
if prop not in ['default', 'const'] # These are reserved names,
# not properties.
]))
required_keys = set(schema.get('required', []))
if outer:
# We want to name the outer Type, so that we can support nested
# references. Note that this may not be fully supported in mypy
# at this time.
info = self._build_typeddict_typeinfo(ctx, self.outer_name,
list(items), list(types),
required_keys)
instance = Instance(info, [])
td = info.typeddict_type
typing_type = td.copy_modified(item_types=list(td.items.values()),
fallback=instance)
# Resolve any forward (nested) references to this Type.
#
# Or not. Per @ilevkivskyi:
#
# > You should never use ForwardRef manually
# > Also it is deprecated and will be removed soon
# > Support for recursive types is limited to proper classes
# > currently
#
# if self.forward_refs:
#
# for fw in self.forward_refs:
# fw.resolve(typing_type)
return typing_type
struct = OrderedDict(zip(items, types))
return TypedDictType(struct, required_keys, fallback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment