On Sat, Oct 1, 2016 at 9:39 PM, Christian Tismer <tis...@stackless.com> wrote:
> The exec() script inherited the __future__ statement!
> It behaved like the future statement were implicitly there.
>
> Is that a bug or a feature?

It's documented, but not very noisily.

https://docs.python.org/2/reference/simple_stmts.html#future-statements

So if you want to isolate the execution environments, you can use
compile() explicitly. Without isolation:

Python 2.7.12+ (default, Sep  1 2016, 20:27:38)
[GCC 6.2.0 20160822] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> exec(compile("print('hello','world')", "-", "exec"))
('hello', 'world')
>>> exec(compile("from __future__ import print_function; 
>>> print('hello','world')", "-", "exec"))
hello world
>>> from __future__ import print_function
>>> exec(compile("print('hello','world')", "-", "exec"))
hello world
>>> exec(compile("from __future__ import print_function; 
>>> print('hello','world')", "-", "exec"))
hello world

With isolation:

>>> exec(compile("print('hello','world')", "-", "exec", 0, 1))
('hello', 'world')
>>> exec(compile("from __future__ import print_function; 
>>> print('hello','world')", "-", "exec", 0, 1))
hello world

So I'd call it a feature, but possibly one that warrants a mention in
the exec and eval docs. Maybe something like:

https://docs.python.org/2/reference/simple_stmts.html#the-exec-statement

[2] When strings are executed, __future__ directives active in the
surrounding context will be active for the compiled code also. If this
is not desired, see the compile() function's dont_inherit parameter.

Would that clarify?

ChrisA
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to