REPL with multiple function definitions

Chris Angelico rosuav at gmail.com
Tue Jun 28 21:13:29 EDT 2022


On 2022年6月29日 at 11:00, Rob Cliffe via Python-list
<python-list at python.org> wrote:
>> On 26/06/2022 23:22, Jon Ribbens via Python-list wrote:
> > On 2022年06月26日, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
> >> This 2-line program
> >>
> >> def f(): pass
> >> def g(): pass
> >>
> >> runs silently (no Exception). But:
> >>
> >> 23:07:02 c:\>python
> >> Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32
> >> bit (Intel)] on win32
> >> Type "help", "copyright", "credits" or "license" for more information.
> >>>>> def f(): pass
> >> ... def g(): pass
> >> File "<stdin>", line 2
> >> def g(): pass
> >> ^
> >> SyntaxError: invalid syntax
> >> Is there a good reason for this?
> > For some reason, the REPL can't cope with one-line blocks like that.
> > If you put a blank line after each one-block line then it will work.
> It's actually not to do with 1-line blocks, just attempting to define 2
> functions "at once":
>>> 22:27:23 C:\>python
> Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32
> bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def f():
> ... return 42
> ... def g():
> File "<stdin>", line 3
> def g():
> ^
> SyntaxError: invalid syntax
> >>>
>> But you are right that adding a blank line after the first function
> definition solves the "problem".

And if you have something where you want to copy and paste multiple
statements, there are a few ways to do it:
1) Put "if 1:" at the top. That makes it a single block, so you can
paste in as much as you like, as long as the only blank line is at the
end.
2) Put the code into a file and then use "python3 -i setup.py". That
runs all the code, then drops you into the REPL in that context.
3) Put the code into a file, and inside the REPL, "from setup import
*". Unlike option 2, this can be done after the beginning of the
session. Downside: editing setup.py and reimporting won't apply your
changes.
ChrisA


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /