3939import traceback
4040from itertools import takewhile
4141from six import itervalues
42+ from types import ModuleType
4243
4344from pygments .token import Token
4445
@@ -77,9 +78,16 @@ def estimate(self):
7778
7879
7980class Interpreter (code .InteractiveInterpreter ):
81+ """Source code interpreter for use in bpython."""
8082
8183 def __init__ (self , locals = None , encoding = None ):
82- """The syntaxerror callback can be set at any time and will be called
84+ """Constructor.
85+
86+ The optional 'locals' argument specifies the dictionary in which code
87+ will be executed; it defaults to a newly created dictionary with key
88+ "__name__" set to "__main__".
89+
90+ The syntaxerror callback can be set at any time and will be called
8391 on a caught syntax error. The purpose for this in bpython is so that
8492 the repl can be instantiated after the interpreter (which it
8593 necessarily must be with the current factoring) and then an exception
@@ -95,6 +103,13 @@ def __init__(self, locals=None, encoding=None):
95103
96104 self .encoding = encoding or sys .getdefaultencoding ()
97105 self .syntaxerror_callback = None
106+
107+ if locals is None :
108+ # instead of messing with sys.modules, we should modify sys.modules
109+ # in the interpreter instance
110+ sys .modules ['__main__' ] = main_mod = ModuleType ('__main__' )
111+ locals = main_mod .__dict__
112+
98113 # Unfortunately code.InteractiveInterpreter is a classic class, so no
99114 # super()
100115 code .InteractiveInterpreter .__init__ (self , locals )
0 commit comments