Skip to content

Commit

Permalink
Don't report [not-instantiable] for fake classes constructed with New…
Browse files Browse the repository at this point in the history
…Type.

PiperOrigin-RevId: 536927203
  • Loading branch information
rchen152 committed Jun 1, 2023
1 parent 6605d4d commit 12b6f87
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
12 changes: 9 additions & 3 deletions pytype/overlays/typing_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,19 +391,25 @@ def call(self, node, func, args, alias_map=None):
# We need the type arg to be an atomic value. If not, we just
# silently return unsolvable.
return node, self.ctx.new_unsolvable(node)
value_arg_name = "val"
if isinstance(type_value, abstract.AnnotationContainer):
type_value = type_value.base_cls
constructor = overlay_utils.make_method(
self.ctx,
node,
name="__init__",
params=[Param(value_arg_name, type_value)])
params=[Param("val", type_value)])
members = abstract.Dict(self.ctx)
members.set_str_item(node, "__init__", constructor)
props = class_mixin.ClassBuilderProperties(
name_var=name_arg,
bases=[type_arg],
class_dict_var=members.to_variable(node))
return self.ctx.make_class(node, props)
node, clsvar = self.ctx.make_class(node, props)
# At runtime, the 'class' created by NewType is simply an identity function,
# so it ignores abstract-ness.
for cls in clsvar.data:
cls.abstract_methods.clear()
return node, clsvar


class Overload(abstract.PyTDFunction):
Expand Down
10 changes: 10 additions & 0 deletions pytype/tests/test_typing2.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,16 @@ def func3(s: MyStr) -> MyStr:
"e2": r".*Expected: \(i: MyInt\)\nActually passed: \(i: int\)",
"e3": r".*Expected:.*val: str\)\nActually passed:.*val: int\)"})

def test_new_type_not_abstract(self):
# At runtime, the 'class' created by NewType is simply an identity function,
# so it ignores abstract-ness.
self.Check("""
from typing import Mapping, NewType
X = NewType('X', Mapping)
def f() -> X:
return X({})
""")

def test_maybe_return(self):
self.Check("""
def f() -> int:
Expand Down

0 comments on commit 12b6f87

Please sign in to comment.