From f4c19b208e4b4864e595ea0183cbb03ec9abea51 Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Wed, 29 Jul 2026 18:07:02 -0700 Subject: [PATCH] Fix strict optional with generic defaults This was regressed in #21526 Fixes #21777 --- mypy/typeanal.py | 2 +- test-data/unit/check-expressions.test | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/mypy/typeanal.py b/mypy/typeanal.py index ff3c8bd2816e1..f6b55fd1d83f8 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -2189,7 +2189,7 @@ def fix_instance( else: unpacked = [arg] for arg in unpacked: - with state.strict_optional_set(options.strict_optional): + with state.strict_optional_set(True): # Gradually expand defaults, as they may depend on previous variables. if tv.has_default(): arg = expand_type(arg, env) diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index 7123285e5eca1..0605c2d8a6fe4 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -1248,6 +1248,28 @@ class SupportsIndex(Protocol): def __index__(self) -> int: ... [builtins fixtures/slice.pyi] +[case testSliceWithPerFileStrictOptional] +# flags: --no-strict-optional +# mypy: strict-optional +"x"[1:] +[file builtins.py] +from typing import Generic, TypeVar + +_StartT = TypeVar("_StartT", covariant=True) +_StopT = TypeVar("_StopT", covariant=True, default=_StartT) +_StepT = TypeVar("_StepT", covariant=True, default=_StartT | _StopT) + +class object: + def __init__(self) -> None: pass +class type: pass +class tuple(Generic[_StartT]): pass +class function: pass +class int: pass +class str: + def __getitem__(self, index: slice[int | None]) -> str: pass +class slice(Generic[_StartT, _StopT, _StepT]): pass +class dict: pass + [case testNoneSliceBounds] from typing import Any a: Any