PyRun_SimpleString doesn't have anywhere to specify compiler flags, but there's a whole host of related functions with more options available. For example, PyRun_SimpleStringFlags
does what PyRun_SimpleString
does, but with a flags
argument to specify compiler flags. __future__
statements executed with PyRun_SimpleStringFlags
can modify the flags
, and the change will be seen by other calls using the same flags
.
You can initialize flags
with future statements, or with the C-level flag definitions. Most of the possible flags aren't listed in the C-api documentation (since the C-api documentation kind of sucks), but you can find them in the __future__
module or in several parts of the Python source code.
>>> import __future__
>>> for name in dir(__future__):
... if name.startswith('CO_'):
... print name
...
CO_FUTURE_ABSOLUTE_IMPORT
CO_FUTURE_DIVISION
CO_FUTURE_PRINT_FUNCTION
CO_FUTURE_UNICODE_LITERALS
CO_FUTURE_WITH_STATEMENT
CO_GENERATOR_ALLOWED
CO_NESTED
For example, you could run a string under the effects of from __future__ import print_function
with
PyCompilerFlags flags = {CO_FUTURE_PRINT_FUNCTION};
PyRun_SimpleStringFlags(command, &flags);
If you want to save the effects of user-executed future statements, you'd save the PyCompilerFlags struct somewhere and use the same one for all calls.
With that said, I don't think automatically applying from __future__ import print_function
is the right thing to do. It'll surprise people expecting the default behavior of whatever interpreter they're on. Also, PyRun_InteractiveOneFlags
might be useful for letting the user input multi-line Python statements.