Python icon indicating copy to clipboard operation
Python copied to clipboard

from __future__ import print_function breaks with file argument

Open dosmoc opened this issue 10 years ago • 0 comments

Issue #23 shows that evaluating the print function imported from __future__ breaks with a syntax error:

    from __future__ import print_function
    print('spam', file=sys.stderr)
Traceback (most recent call last):
  File "/home/dosmo/repos/LightTable/builds/lighttable-0.8.0-linux/resources/app/plugins/Python/py-src/ltmain.py", line 199, in handleEval
    code= compile(ensureUtf(code), ensureUtf(data[2]["name"]), 'exec')
  File "future-test.py", line 4
    print('spam', file=sys.stdout)
                      ^
SyntaxError: invalid syntax

This is different from the other problem printing to sys.stderr. It looks as if the compile function needs to receive the proper compiler flags for the syntax changes from __future__ in order for the plugin to operate correctly. Docs for the compile function and the future module.

From a Python2 interpreter this fails with the syntax error:

>>> compile("print('spam', file=sys.stdout)", "testname", "exec")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "testname", line 1
    print('spam', file=sys.stdout)
                      ^
SyntaxError: invalid syntax

Where using the compiler flag for the print_function does not:

>>> __future__.print_function.compiler_flag
65536
>>> compile("print('spam', file=sys.stdout)", "testname", "exec", flags=65536)
<code object <module> at 0x7fb50699ecb0, file "testname", line 1>

It may be possible to fix this by checking if any future statements are executed, obtaining the proper compiler flags from them, and feeding them to later calls to compile.

dosmoc avatar Sep 07 '15 17:09 dosmoc