@@ -240,6 +240,10 @@ class ModuleScope(Scope):
240
240
pass
241
241
242
242
243
+ class DoctestScope (ModuleScope ):
244
+ pass
245
+
246
+
243
247
# Globally defined names which are not attributes of the builtins module, or
244
248
# are only present on some platforms.
245
249
_MAGIC_GLOBALS = ['__file__' , '__builtins__' , 'WindowsError' ]
@@ -625,7 +629,7 @@ def handleDoctests(self, node):
625
629
if not examples :
626
630
return
627
631
node_offset = self .offset or (0 , 0 )
628
- self .pushScope ()
632
+ self .pushScope (DoctestScope )
629
633
underscore_in_builtins = '_' in self .builtIns
630
634
if not underscore_in_builtins :
631
635
self .builtIns .add ('_' )
@@ -681,9 +685,14 @@ def GLOBAL(self, node):
681
685
"""
682
686
Keep track of globals declarations.
683
687
"""
684
- # In doctests, the global scope is an anonymous function at index 1.
685
- global_scope_index = 1 if self .withDoctest else 0
686
- global_scope = self .scopeStack [global_scope_index ]
688
+ for i , scope in enumerate (self .scopeStack ):
689
+ if isinstance (scope , DoctestScope ):
690
+ global_scope_index = i
691
+ global_scope = scope
692
+ break
693
+ else :
694
+ global_scope_index = 0
695
+ global_scope = self .scopeStack [0 ]
687
696
688
697
# Ignore 'global' statement in global scope.
689
698
if self .scope is not global_scope :
0 commit comments