@@ -257,6 +257,7 @@ def __init__(self, func_def, code_list, code_str, global_ctx):
257
257
self .decorators = []
258
258
self .global_names = set ()
259
259
self .nonlocal_names = set ()
260
+ self .local_names = None
260
261
self .local_sym_table = {}
261
262
self .doc_string = ast .get_docstring (func_def )
262
263
self .num_posn_arg = len (self .func_def .args .args ) - len (self .defaults )
@@ -562,14 +563,17 @@ async def resolve_nonlocals(self, ast_ctx):
562
563
nonlocal_names = set ()
563
564
global_names = set ()
564
565
var_names = set (args )
565
- local_names = set (args )
566
+ self . local_names = set (args )
566
567
for stmt in self .func_def .body :
567
568
self .has_closure = self .has_closure or isinstance (
568
569
stmt , (ast .FunctionDef , ast .ClassDef , ast .AsyncFunctionDef )
569
570
)
570
571
var_names = var_names .union (
571
572
await ast_ctx .get_names (
572
- stmt , nonlocal_names = nonlocal_names , global_names = global_names , local_names = local_names ,
573
+ stmt ,
574
+ nonlocal_names = nonlocal_names ,
575
+ global_names = global_names ,
576
+ local_names = self .local_names ,
573
577
)
574
578
)
575
579
for var_name in var_names :
@@ -580,7 +584,7 @@ async def resolve_nonlocals(self, ast_ctx):
580
584
if var_name in global_names :
581
585
continue
582
586
583
- if var_name in local_names and var_name not in nonlocal_names :
587
+ if var_name in self . local_names and var_name not in nonlocal_names :
584
588
if self .has_closure :
585
589
self .local_sym_table [var_name ] = EvalLocalVar (var_name )
586
590
continue
@@ -1426,6 +1430,8 @@ async def ast_name(self, arg):
1426
1430
if arg .id in self .local_sym_table :
1427
1431
return self .local_sym_table [arg .id ]
1428
1432
if arg .id in self .global_sym_table :
1433
+ if self .curr_func and arg .id in self .curr_func .local_names :
1434
+ raise UnboundLocalError (f"local variable '{ arg .id } ' referenced before assignment" )
1429
1435
return self .global_sym_table [arg .id ]
1430
1436
if arg .id in BUILTIN_AST_FUNCS_FACTORY :
1431
1437
return BUILTIN_AST_FUNCS_FACTORY [arg .id ](self )
0 commit comments