Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> P
fallback=named_type("builtins.function"),
)
result: FunctionLike = class_callable(sig, info, fallback, None, is_new=False)
if allow_cache:
if allow_cache and state.strict_optional:
info.type_object_type = result
return result

Expand All @@ -230,7 +230,9 @@ def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> P
assert isinstance(method.type, FunctionLike) # is_valid_constructor() ensures this
t = method.type
result = type_object_type_from_function(t, info, method.info, fallback, is_new)
if allow_cache:
# Only write cached result is strict_optional=True, otherwise we may get
# inconsistent behaviour because of union simplification.
if allow_cache and state.strict_optional:
info.type_object_type = result
return result

Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -9273,3 +9273,19 @@ class Bar:
[file foo.py]
class Bar:
...

[case testConstructorWithoutStrictOptionalNoCache]
import mod
a = mod.NT(x=None) # OK

[file typ.py]
from typing import NamedTuple, Optional
NT = NamedTuple("NT", [("x", Optional[str])])

[file mod.py]
# mypy: no-strict-optional
from typ import NT

def f() -> NT:
return NT(x='')
[builtins fixtures/tuple.pyi]
Loading