8000 Additional validation for TypeVar defaults (PEP 696) by cdce8p · Pull Request #15442 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Additional validation for TypeVar defaults (PEP 696) #15442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Additional TypeVar defaults validation
  • Loading branch information
cdce8p committed Jun 15, 2023
commit cebfe024b4582cbdf61edd1acb042205396d458d
9 changes: 9 additions & 0 deletions mypy/checkexpr.py
9 changes: 9 additions & 0 deletions test-data/unit/check-typevar-defaults.test
Original file line number Diff line number Diff line change
Expand Up @@ -5197,6 +5197,15 @@ def visit_temp_node(self, e: TempNode) -> Type:
return e.type

def visit_type_var_expr(self, e: TypeVarExpr) -> Type:
p_default = get_proper_type(e.default)
if not (
isinstance(p_default, AnyType)
and p_default.type_of_any == TypeOfAny.from_omitted_generics
):
if not is_subtype(p_default, e.upper_bound):
self.chk.fail("TypeVar default must be a subtype of the bound type", e)
if e.values and not any(p_default == value for value in e.values):
self.chk.fail("TypeVar default must be one of the constraint types", e)
return AnyType(TypeOfAny.special_form)

def visit_paramspec_expr(self, e: ParamSpecExpr) -> Type:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,12 @@ Ts1 = TypeVarTuple("Ts1", default=2) # E: The default argument to TypeVarTuple m
Ts2 = TypeVarTuple("Ts2", default=int) # E: The default argument to TypeVarTuple must be an Unpacked tuple
Ts3 = TypeVarTuple("Ts3", default=Tuple[int]) # E: The default argument to TypeVarTuple must be an Unpacked tuple
[builtins fixtures/tuple.pyi]

[case testTypeVarDefaultsInvalid2]
from typing import TypeVar, List, Union

T1 = TypeVar("T1", bound=str, default=int) # E: TypeVar default must be a subtype of the bound type
T2 = TypeVar("T2", bound=List[str], default=List[int]) # E: TypeVar default must be a subtype of the bound type
T3 = TypeVar("T3", int, str, default=bytes) # E: TypeVar default must be one of the constraint types
T4 = TypeVar("T4", int, str, default=Union[int, str]) # E: TypeVar default must be one of the constraint types
T5 = TypeVar("T5", float, str, default=int) # E: TypeVar default must be one of the constraint types
0