44
44
"""
45
45
46
46
from typing import (
47
- List , Dict , Set , Tuple , cast , Any , TypeVar , Union , Optional , Callable
47
+ List , Dict , Set , Tuple , cast , TypeVar , Union , Optional , Callable
48
48
)
49
49
50
50
from mypy .nodes import (
@@ -280,9 +280,7 @@ def visit_func_def(self, defn: FuncDef) -> None:
280
280
if defn .name () in self .type .names :
281
281
# Redefinition. Conditional redefinition is okay.
282
282
n = self .type .names [defn .name ()].node
283
- if self .is_conditional_func (n , defn ):
284
- defn .original_def = cast (FuncDef , n )
285
- else :
283
+ if not self .set_original_def (n , defn ):
286
284
self .name_already_defined (defn .name (), defn )
287
285
self .type .names [defn .name ()] = SymbolTableNode (MDEF , defn )
288
286
self .prepare_method_signature (defn )
@@ -292,9 +290,7 @@ def visit_func_def(self, defn: FuncDef) -> None:
292
290
if defn .name () in self .locals [- 1 ]:
293
291
# Redefinition. Conditional redefinition is okay.
294
292
n = self .locals [- 1 ][defn .name ()].node
295
- if self .is_conditional_func (n , defn ):
296
- defn .original_def = cast (FuncDef , n )
297
- else :
293
+ if not self .set_original_def (n , defn ):
298
294
self .name_already_defined (defn .name (), defn )
299
295
else :
300
296
self .add_local (defn , defn )
@@ -304,11 +300,7 @@ def visit_func_def(self, defn: FuncDef) -> None:
304
300
symbol = self .globals .get (defn .name ())
305
301
if isinstance (symbol .node , FuncDef ) and symbol .node != defn :
306
302
# This is redefinition. Conditional redefinition is okay.
307
- original_def = symbol .node
308
- if self .is_conditional_func (original_def , defn ):
309
- # Conditional function definition -- multiple defs are ok.
310
- defn .original_def = original_def
311
- else :
303
+ if not self .set_original_def (symbol .node , defn ):
312
304
# Report error.
313
305
self .check_no_global (defn .name (), defn , True )
314
306
if phase_info == FUNCTION_FIRST_PHASE_POSTPONE_SECOND :
@@ -341,19 +333,22 @@ def prepare_method_signature(self, func: FuncDef) -> None:
341
333
leading_type = self .class_type (self .type )
342
334
else :
343
335
leading_type = fill_typevars (self .type )
344
- sig = cast (FunctionLike , func .type )
345
- func .type = replace_implicit_first_type (sig , leading_type )
336
+ func .type = replace_implicit_first_type (functype , leading_type )
346
337
347
- def is_conditional_func (self , previous : Node , new : FuncDef ) -> bool :
348
- """Does 'new' conditionally redefine 'previous'?
338
+ def set_original_def (self , previous : Node , new : FuncDef ) -> bool :
339
+ """If 'new' conditionally redefine 'previous', set 'previous' as original
349
340
350
341
We reject straight redefinitions of functions, as they are usually
351
342
a programming error. For example:
352
343
353
344
. def f(): ...
354
345
. def f(): ... # Error: 'f' redefined
355
346
"""
356
- return isinstance (previous , (FuncDef , Var )) and new .is_conditional
347
+ if isinstance (previous , (FuncDef , Var )) and new .is_conditional :
348
+ new .original_def = previous
349
+ return True
350
+ else :
351
+ return False
357
352
358
353
def update_function_type_variables (self , defn : FuncDef ) -> None :
359
354
"""Make any type variables in the signature of defn explicit.
@@ -362,8 +357,8 @@ def update_function_type_variables(self, defn: FuncDef) -> None:
362
357
if defn is generic.
363
358
"""
364
359
if defn .type :
365
- functype = cast ( CallableType , defn .type )
366
- typevars = self .infer_type_variables (functype )
360
+ assert isinstance ( defn .type , CallableType )
361
+ typevars = self .infer_type_variables (defn . type )
367
362
# Do not define a new type variable if already defined in scope.
368
363
typevars = [(name , tvar ) for name , tvar in typevars
369
364
if not self .is_defined_type_var (name , defn )]
@@ -373,7 +368,7 @@ def update_function_type_variables(self, defn: FuncDef) -> None:
373
368
tvar [1 ].values , tvar [1 ].upper_bound ,
374
369
tvar [1 ].variance )
375
370
for i , tvar in enumerate (typevars )]
376
- functype .variables = defs
371
+ defn . type .variables = defs
377
372
378
373
def infer_type_variables (self ,
379
374
type : CallableType ) -> List [Tuple [str , TypeVarExpr ]]:
@@ -387,8 +382,7 @@ def infer_type_variables(self,
387
382
tvars .append (tvar_expr )
388
383
return list (zip (names , tvars ))
389
384
390
- def find_type_variables_in_type (
391
- self , type : Type ) -> List [Tuple [str , TypeVarExpr ]]:
385
+ def find_type_variables_in_type (self , type : Type ) -> List [Tuple [str , TypeVarExpr ]]:
392
386
"""Return a list of all unique type variable references in type.
393
387
394
388
This effectively does partial name binding, results of which are mostly thrown away.
@@ -398,7 +392,8 @@ def find_type_variables_in_type(
398
392
name = type .name
399
393
node = self .lookup_qualified (name , type )
400
394
if node and node .kind == UNBOUND_TVAR :
401
- result .append ((name , cast (TypeVarExpr , node .node )))
395
+ assert isinstance (node .node , TypeVarExpr )
396
+ result .append ((name , node .node ))
402
397
for arg in type .args :
403
398
result .extend (self .find_type_variables_in_type (arg ))
404
399
elif isinstance (type , TypeList ):
@@ -425,8 +420,9 @@ def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
425
420
item .is_overload = True
426
421
item .func .is_overload = True
427
422
item .accept (self )
428
- t .append (cast (CallableType , function_type (item .func ,
429
- self .builtin_type ('builtins.function' ))))
423
+ callable = function_type (item .func , self .builtin_type ('builtins.function' ))
424
+ assert isinstance (callable , CallableType )
425
+ t .append (callable )
430
426
if item .func .is_property and i == 0 :
431
427
# This defines a property, probably with a setter and/or deleter.
432
428
self .analyze_property_with_multi_part_definition (defn )
@@ -524,8 +520,9 @@ def add_func_type_variables_to_symbol_table(
524
520
nodes = [] # type: List[SymbolTableNode]
525
521
if defn .type :
526
522
tt = defn .type
523
+ assert isinstance (tt , CallableType )
524
+ items = tt .variables
527
525
names = self .type_var_names ()
528
- items = cast (CallableType , tt ).variables
529
526
for item in items :
530
527
name = item .name
531
528
if name in names :
@@ -549,7 +546,8 @@ def bind_type_var(self, fullname: str, tvar_def: TypeVarDef,
549
546
return node
550
547
551
548
def check_function_signature (self , fdef : FuncItem ) -> None :
552
- sig = cast (CallableType , fdef .type )
549
+ sig = fdef .type
550
+ assert isinstance (sig , CallableType )
553
551
if len (sig .arg_types ) < len (fdef .arguments ):
554
552
self .fail ('Type signature has too few arguments' , fdef )
555
553
# Add dummy Any arguments to prevent crashes later.
@@ -725,7 +723,8 @@ def analyze_unbound_tvar(self, t: Type) -> Tuple[str, TypeVarExpr]:
725
723
unbound = t
726
724
sym = self .lookup_qualified (unbound .name , unbound )
727
725
if sym is not None and sym .kind == UNBOUND_TVAR :
728
- return unbound .name , cast (TypeVarExpr , sym .node )
726
+ assert isinstance (sym .node , TypeVarExpr )
727
+ return unbound .name , sym .node
729
728
return None
730
729
731
730
def analyze_namedtuple_classdef (self , defn : ClassDef ) -> bool :
@@ -922,13 +921,15 @@ def class_type(self, info: TypeInfo) -> Type:
922
921
923
922
def named_type (self , qualified_name : str , args : List [Type ] = None ) -> Instance :
924
923
sym = self .lookup_qualified (qualified_name , None )
925
- return Instance (cast (TypeInfo , sym .node ), args or [])
924
+ assert isinstance (sym .node , TypeInfo )
925
+ return Instance (sym .node , args or [])
926
926
927
927
def named_type_or_none (self , qualified_name : str , args : List [Type ] = None ) -> Instance :
928
928
sym = self .lookup_fully_qualified_or_none (qualified_name )
929
929
if not sym :
930
930
return None
931
- return Instance (cast (TypeInfo , sym .node ), args or [])
931
+ assert isinstance (sym .node , TypeInfo )
932
+ return Instance (sym .node , args or [])
932
933
933
934
def bind_class_type_variables_in_symbol_table (
934
935
self , info : TypeInfo ) -> List [SymbolTableNode ]:
@@ -1300,11 +1301,10 @@ def analyze_lvalue(self, lval: Lvalue, nested: bool = False,
1300
1301
lval .accept (self )
1301
1302
elif (isinstance (lval , TupleExpr ) or
1302
1303
isinstance (lval , ListExpr )):
1303
- items = cast ( Any , lval ) .items
1304
+ items = lval .items
1304
1305
if len (items ) == 0 and isinstance (lval , TupleExpr ):
1305
1306
self .fail ("Can't assign to ()" , lval )
1306
- self .analyze_tuple_or_list_lvalue (cast (Union [ListExpr , TupleExpr ], lval ),
1307
- add_global , explicit_type )
1307
+ self .analyze_tuple_or_list_lvalue (lval , add_global , explicit_type )
1308
1308
elif isinstance (lval , StarExpr ):
1309
1309
if nested :
1310
1310
self .analyze_lvalue (lval .expr , nested , add_global , explicit_type )
@@ -1318,9 +1318,7 @@ def analyze_tuple_or_list_lvalue(self, lval: Union[ListExpr, TupleExpr],
1318
1318
explicit_type : bool = False ) -> None :
1319
1319
"""Analyze an lvalue or assignment target that is a list or tuple."""
1320
1320
items = lval .items
1321
- star_exprs = [cast (StarExpr , item )
1322
- for item in items
1323
- if isinstance (item , StarExpr )]
1321
+ star_exprs = [item for item in items if isinstance (item , StarExpr )]
1324
1322
1325
1323
if len (star_exprs ) > 1 :
1326
1324
self .fail ('Two starred expressions in assignment' , lval )
@@ -1452,14 +1450,14 @@ def check_newtype_args(self, name: str, call: CallExpr, context: Context) -> Opt
1452
1450
if not isinstance (args [0 ], (StrExpr , BytesExpr , UnicodeExpr )):
1453
1451
self .fail ("Argument 1 to NewType(...) must be a string literal" , context )
1454
1452
has_failed = True
1455
- elif cast ( StrExpr , call . args [0 ]) .value != name :
1453
+ elif args [0 ].value != name :
1456
1454
msg = "String argument 1 '{}' to NewType(...) does not match variable name '{}'"
1457
- self .fail (msg .format (cast ( StrExpr , call . args [0 ]) .value , name ), context )
1455
+ self .fail (msg .format (args [0 ].value , name ), context )
1458
1456
has_failed = True
1459
1457
1460
1458
# Check second argument
1461
1459
try :
1462
- unanalyzed_type = expr_to_unanalyzed_type (call . args [1 ])
1460
+ unanalyzed_type = expr_to_unanalyzed_type (args [1 ])
1463
1461
except TypeTranslationError :
1464
1462
self .fail ("Argument 2 to NewType(...) must be a valid type" , context )
1465
1463
return None
@@ -1497,7 +1495,8 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> None:
1497
1495
if not call :
1498
1496
return
1499
1497
1500
- lvalue = cast (NameExpr , s .lvalues [0 ])
1498
+ lvalue = s .lvalues [0 ]
1499
+ assert isinstance (lvalue , NameExpr )
1501
1500
name = lvalue .name
1502
1501
if not lvalue .is_def :
1503
1502
if s .type :
@@ -1538,9 +1537,9 @@ def check_typevar_name(self, call: CallExpr, name: str, context: Context) -> boo
1538
1537
or not call .arg_kinds [0 ] == ARG_POS ):
1539
1538
self .fail ("TypeVar() expects a string literal as first argument" , context )
1540
1539
return False
1541
- if cast ( StrExpr , call .args [0 ]) .value != name :
1540
+ elif call .args [0 ].value != name :
1542
1541
msg = "String argument 1 '{}' to TypeVar(...) does not match variable name '{}'"
1543
- self .fail (msg .format (cast ( StrExpr , call .args [0 ]) .value , name ), context )
1542
+ self .fail (msg .format (call .args [0 ].value , name ), context )
1544
1543
return False
1545
1544
return True
1546
1545
@@ -2308,7 +2307,8 @@ def visit_member_expr(self, expr: MemberExpr) -> None:
2308
2307
# This branch handles the case foo.bar where foo is a module.
2309
2308
# In this case base.node is the module's MypyFile and we look up
2310
2309
# bar in its namespace. This must be done for all types of bar.
2311
- file = cast (MypyFile , base .node )
2310
+ file = base .node
2311
+ assert isinstance (file , MypyFile )
2312
2312
n = file .names .get (expr .name , None ) if file is not None else None
2313
2313
if n :
2314
2314
n = self .normalize_type_alias (n , expr )
@@ -2513,7 +2513,8 @@ def lookup(self, name: str, ctx: Context) -> SymbolTableNode:
2513
2513
# 5. Builtins
2514
2514
b = self .globals .get ('__builtins__' , None )
2515
2515
if b :
2516
- table = cast (MypyFile , b .node ).names
2516
+ assert isinstance (b .node , MypyFile )
2517
+ table = b .node .names
2517
2518
if name in table :
2518
2519
if name [0 ] == "_" and name [1 ] != "_" :
2519
2520
self .name_not_defined (name , ctx )
@@ -2568,8 +2569,8 @@ def lookup_qualified(self, name: str, ctx: Context) -> SymbolTableNode:
2568
2569
2569
2570
def builtin_type (self , fully_qualified_name : str ) -> Instance :
2570
2571
node = self .lookup_fully_qualified (fully_qualified_name )
2571
- info = cast ( TypeInfo , node .node )
2572
- return Instance (info , [])
2572
+ assert isinstance ( node .node , TypeInfo )
2573
+ return Instance (node . node , [])
2573
2574
2574
2575
def lookup_fully_qualified (self , name : str ) -> SymbolTableNode :
2575
2576
"""Lookup a fully qualified name.
@@ -2581,10 +2582,12 @@ def lookup_fully_qualified(self, name: str) -> SymbolTableNode:
2581
2582
parts = name .split ('.' )
2582
2583
n = self .modules [parts [0 ]]
2583
2584
for i in range (1 , len (parts ) - 1 ):
2584
- n = cast (MypyFile , n .names [parts [i ]].node )
2585
- return n .names [parts [- 1 ]]
2585
+ next_sym = n .names [parts [i ]]
2586
+ assert isinstance (next_sym .node , MypyFile )
2587
+ n = next_sym .node
2588
+ return n .names .get (parts [- 1 ])
2586
2589
2587
- def lookup_fully_qualified_or_none (self , name : str ) -> SymbolTableNode :
2590
+ def lookup_fully_qualified_or_none (self , name : str ) -> Optional [ SymbolTableNode ] :
2588
2591
"""Lookup a fully qualified name.
2589
2592
2590
2593
Assume that the name is defined. This happens in the global namespace -- the local
@@ -2597,7 +2600,8 @@ def lookup_fully_qualified_or_none(self, name: str) -> SymbolTableNode:
2597
2600
next_sym = n .names .get (parts [i ])
2598
2601
if not next_sym :
2599
2602
return None
2600
- n = cast (MypyFile , next_sym .node )
2603
+ assert isinstance (next_sym .node , MypyFile )
2604
+ n = next_sym .node
2601
2605
return n .names .get (parts [- 1 ])
2602
2606
2603
2607
def qualified_name (self , n : str ) -> str :
@@ -2811,11 +2815,7 @@ def visit_func_def(self, func: FuncDef) -> None:
2811
2815
# Ah this is an imported name. We can't resolve them now, so we'll postpone
2812
2816
# this until the main phase of semantic analysis.
2813
2817
return
2814
- original_def = original_sym .node
2815
- if sem .is_conditional_func (original_def , func ):
2816
- # Conditional function definition -- multiple defs are ok.
2817
- func .original_def = cast (FuncDef , original_def )
2818
- else :
2818
+ if not sem .set_original_def (original_sym .node , func ):
2819
2819
# Report error.
2820
2820
sem .check_no_global (func .name (), func )
2821
2821
else :
@@ -3055,10 +3055,11 @@ def fill_typevars(typ: TypeInfo) -> Union[Instance, TupleType]:
3055
3055
def replace_implicit_first_type (sig : FunctionLike , new : Type ) -> FunctionLike :
3056
3056
if isinstance (sig , CallableType ):
3057
3057
return sig .copy_modified (arg_types = [new ] + sig .arg_types [1 :])
3058
- else :
3059
- sig = cast (Overloaded , sig )
3058
+ elif isinstance (sig , Overloaded ):
3060
3059
return Overloaded ([cast (CallableType , replace_implicit_first_type (i , new ))
3061
3060
for i in sig .items ()])
3061
+ else :
3062
+ assert False
3062
3063
3063
3064
3064
3065
def set_callable_name (sig : Type , fdef : FuncDef ) -> Type :
0 commit comments