Skip to content

Commit 675246d

Browse files
Clarify about Interpreter.exec().
1 parent 72e46fb commit 675246d

File tree

1 file changed

+49
-16
lines changed

1 file changed

+49
-16
lines changed

Doc/howto/multiple-interpreters.rst

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -133,23 +133,12 @@ builtin :func:`exec` using that interpreter::
133133

134134
(See :meth:`Interpreter.exec`.)
135135

136-
Calling a simple function in an interpreter works the same way::
136+
Calls are also supported.
137+
See :ref:`the next section <interp-tutorial-calls>`.
137138

138-
from concurrent import interpreters
139-
140-
def script():
141-
print('spam!')
142-
143-
if __name__ == '__main__':
144-
interp = interpreters.create()
145-
interp.call(script)
146-
# prints: spam!
147-
148-
(See :meth:`Interpreter.call`.)
149-
150-
When it runs, the code is executed using the interpreter's
151-
:mod:`!__main__` module, just like a Python process normally does when
152-
invoked from the command-line::
139+
When :meth:`Interpreter.exec` runs, the code is executed using the
140+
interpreter's :mod:`!__main__` module, just like a Python process
141+
normally does when invoked from the command-line::
153142

154143
from concurrent import interpreters
155144

@@ -206,6 +195,50 @@ It's also fairly easy to simulate the other forms of the Python CLI::
206195
That's more or less what the ``python`` executable is doing for each
207196
of those cases.
208197

198+
You can also exec any function that doesn't take any arguments, nor
199+
returns anything. Closures are not allowed but other nested functions
200+
are. It works the same as if you had passed the script corresponding
201+
to the function's body::
202+
203+
from concurrent import interpreters
204+
205+
def script():
206+
print('spam!')
207+
208+
def get_script():
209+
def nested():
210+
print('eggs!')
211+
return nested
212+
213+
if __name__ == '__main__':
214+
interp = interpreters.create()
215+
216+
interp.exec(script)
217+
# prints: spam!
218+
219+
script2 = get_script()
220+
interp.exec(script2)
221+
# prints: eggs!
222+
223+
Any referenced globals are resolved relative to the interpreter's
224+
:mod:`!__main__` module, just like happens for scripts, rather than
225+
the original function's module::
226+
227+
from concurrent import interpreters
228+
229+
def script():
230+
print(__name__)
231+
232+
if __name__ == '__main__':
233+
interp = interpreters.create()
234+
interp.exec(script)
235+
# prints: __main__
236+
237+
One practical difference is that with a script function you get syntax
238+
highlighting in your editor. With script text you probably don't.
239+
240+
.. _interp-tutorial-calls:
241+
209242
Calling a Function in an Interpreter
210243
------------------------------------
211244

0 commit comments

Comments
 (0)