@@ -240,6 +240,10 @@ class ModuleScope(Scope):
240240 pass
241241
242242
243+ class DoctestScope (ModuleScope ):
244+ pass
245+
246+
243247# Globally defined names which are not attributes of the builtins module, or
244248# are only present on some platforms.
245249_MAGIC_GLOBALS = ['__file__' , '__builtins__' , 'WindowsError' ]
@@ -625,7 +629,7 @@ def handleDoctests(self, node):
625629 if not examples :
626630 return
627631 node_offset = self .offset or (0 , 0 )
628- self .pushScope ()
632+ self .pushScope (DoctestScope )
629633 underscore_in_builtins = '_' in self .builtIns
630634 if not underscore_in_builtins :
631635 self .builtIns .add ('_' )
@@ -681,9 +685,14 @@ def GLOBAL(self, node):
681685 """
682686 Keep track of globals declarations.
683687 """
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 ]
687696
688697 # Ignore 'global' statement in global scope.
689698 if self .scope is not global_scope :
0 commit comments