Index: Objects/frameobject.c =================================================================== --- Objects/frameobject.c (revision 64228) +++ Objects/frameobject.c (working copy) @@ -881,9 +881,11 @@ if (ncells || nfreevars) { dict_to_map(co->co_cellvars, ncells, locals, fast + co->co_nlocals, 1, clear); - dict_to_map(co->co_freevars, nfreevars, - locals, fast + co->co_nlocals + ncells, 1, - clear); + if (co->co_flags & CO_OPTIMIZED) { + dict_to_map(co->co_freevars, nfreevars, + locals, fast + co->co_nlocals + ncells, 1, + clear); + } } PyErr_Restore(error_type, error_value, error_traceback); } Index: Lib/test/test_scope.py =================================================================== --- Lib/test/test_scope.py (revision 64228) +++ Lib/test/test_scope.py (working copy) @@ -519,6 +519,24 @@ self.assert_("x" not in varnames) self.assert_("y" in varnames) + def testLocalsClass_WithTrace(self): + # Issue23728: after the trace trace function returns, the + # locals() dictionary is used to update all variables, this + # used to include free variables. But in class statements, + # free variables are not inserted... + import sys + sys.settrace(lambda a,b,c:None) + try: + x = 12 + + class C: + def f(self): + return x + + assert x == 12 # Used to raise UnboundLocalError + finally: + sys.settrace(None) + def testBoundAndFree(self): # var is bound and free in class