@@ -161,14 +161,17 @@ def evaluate(
161161 # as a way of emulating annotation scopes when calling `eval()`
162162 type_params = getattr (owner , "__type_params__" , None )
163163
164- # Type parameters exist in their own scope, which is logically
165- # between the locals and the globals. We simulate this by adding
166- # them to the globals. Similar reasoning applies to nonlocals stored in cells.
167- if type_params is not None or isinstance (self .__cell__ , dict ):
164+ # Nonlocals logically sit between the locals and the globals. We simulate this
165+ # by overriding the globals.
166+ if isinstance (self .__cell__ , dict ):
168167 globals = dict (globals )
168+
169+ # Type parameters exist in their own scope, which is logically
170+ # between the locals and the globals.
171+ type_param_scope = {}
169172 if type_params is not None :
170173 for param in type_params :
171- globals [param .__name__ ] = param
174+ type_param_scope [param .__name__ ] = param
172175 if isinstance (self .__cell__ , dict ):
173176 for cell_name , cell_value in self .__cell__ .items ():
174177 try :
@@ -182,6 +185,8 @@ def evaluate(
182185 if arg .isidentifier () and not keyword .iskeyword (arg ):
183186 if arg in locals :
184187 return locals [arg ]
188+ elif arg in type_param_scope :
189+ return type_param_scope [arg ]
185190 elif arg in globals :
186191 return globals [arg ]
187192 elif hasattr (builtins , arg ):
@@ -193,15 +198,15 @@ def evaluate(
193198 else :
194199 code = self .__forward_code__
195200 try :
196- return eval (code , globals = globals , locals = locals )
201+ return eval (code , globals = globals , locals = { ** type_param_scope , ** locals } )
197202 except Exception :
198203 if not is_forwardref_format :
199204 raise
200205
201206 # All variables, in scoping order, should be checked before
202207 # triggering __missing__ to create a _Stringifier.
203208 new_locals = _StringifierDict (
204- {** builtins .__dict__ , ** globals , ** locals },
209+ {** builtins .__dict__ , ** globals , ** type_param_scope , ** locals },
205210 globals = globals ,
206211 owner = owner ,
207212 is_class = self .__forward_is_class__ ,
0 commit comments