Skip to content

Commit

Permalink
Unify a codepath in typevarlike semanal (#12480)
Browse files Browse the repository at this point in the history
  • Loading branch information
jhance authored Mar 28, 2022
1 parent bd53039 commit 7ac5a19
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 18 deletions.
34 changes: 18 additions & 16 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3093,14 +3093,8 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool:
if not call:
return False

lvalue = s.lvalues[0]
assert isinstance(lvalue, NameExpr)
if s.type:
self.fail("Cannot declare the type of a type variable", s)
return False

name = lvalue.name
if not self.check_typevarlike_name(call, name, s):
name = self.extract_typevarlike_name(s, call)
if name is None:
return False

# Constraining types
Expand Down Expand Up @@ -3279,6 +3273,20 @@ def process_typevar_parameters(self, args: List[Expression],
variance = INVARIANT
return variance, upper_bound

def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> Optional[str]:
if not call:
return None

lvalue = s.lvalues[0]
assert isinstance(lvalue, NameExpr)
if s.type:
self.fail("Cannot declare the type of a TypeVar or similar construct", s)
return None

if not self.check_typevarlike_name(call, lvalue.name, s):
return None
return lvalue.name

def process_paramspec_declaration(self, s: AssignmentStmt) -> bool:
"""Checks if s declares a ParamSpec; if yes, store it in symbol table.
Expand All @@ -3293,14 +3301,8 @@ def process_paramspec_declaration(self, s: AssignmentStmt) -> bool:
if not call:
return False

lvalue = s.lvalues[0]
assert isinstance(lvalue, NameExpr)
if s.type:
self.fail("Cannot declare the type of a parameter specification", s)
return False

name = lvalue.name
if not self.check_typevarlike_name(call, name, s):
name = self.extract_typevarlike_name(s, call)
if name is None:
return False

# ParamSpec is different from a regular TypeVar:
Expand Down
4 changes: 2 additions & 2 deletions test-data/unit/semanal-errors.test
Original file line number Diff line number Diff line change
Expand Up @@ -1081,7 +1081,7 @@ x = TypeVar('x') # E: Cannot redefine "x" as a type variable

[case testTypevarWithType]
from typing import TypeVar
x = TypeVar('x') # type: int # E: Cannot declare the type of a type variable
x = TypeVar('x') # type: int # E: Cannot declare the type of a TypeVar or similar construct
[out]

[case testRedefineTypevar]
Expand Down Expand Up @@ -1432,7 +1432,7 @@ from typing_extensions import ParamSpec

TParams = ParamSpec('TParams')
TP = ParamSpec('?') # E: String argument 1 "?" to ParamSpec(...) does not match variable name "TP"
TP2: int = ParamSpec('TP2') # E: Cannot declare the type of a parameter specification
TP2: int = ParamSpec('TP2') # E: Cannot declare the type of a TypeVar or similar construct

[out]

Expand Down

0 comments on commit 7ac5a19

Please sign in to comment.