[New-bugs-announce] [issue17294] compile-flag for single-execution to return value instead of printing it
Albert Zeyer
report at bugs.python.org
Mon Feb 25 14:11:26 CET 2013
New submission from Albert Zeyer:
`compile(s, "<interactive>", "single")` would generate a code object which prints the value of the evaluated string if that is an expression. This is what you would normally want in a REPL.
Instead of printing the value, it might make more sense to return it and to leave it to the developer - there are many cases where it shouldn't end up on stdout but somewhere else.
There could be an additional compile-flag which would make a code-object returning the value instead of printing it.
Note that I have come up with a workaround:
def interactive_py_compile(source, filename="<interactive>"):
c = compile(source, filename, "single")
# we expect this at the end:
# PRINT_EXPR
# LOAD_CONST
# RETURN_VALUE
import dis
if ord(c.co_code[-5]) != dis.opmap["PRINT_EXPR"]:
return c
assert ord(c.co_code[-4]) == dis.opmap["LOAD_CONST"]
assert ord(c.co_code[-1]) == dis.opmap["RETURN_VALUE"]
code = c.co_code[:-5]
code += chr(dis.opmap["RETURN_VALUE"])
CodeArgs = [
"argcount", "nlocals", "stacksize", "flags", "code",
"consts", "names", "varnames", "filename", "name",
"firstlineno", "lnotab", "freevars", "cellvars"]
c_dict = dict([(arg, getattr(c, "co_" + arg)) for arg in CodeArgs])
c_dict["code"] = code
import types
c = types.CodeType(*[c_dict[arg] for arg in CodeArgs])
return c
My related StackOverflow question:
http://stackoverflow.com/questions/15059372/python-use-of-eval-in-interactive-terminal-how-to-get-return-value-what-compi
----------
components: Interpreter Core
messages: 182934
nosy: Albert.Zeyer
priority: normal
severity: normal
status: open
title: compile-flag for single-execution to return value instead of printing it
type: enhancement
versions: Python 2.7, Python 3.1, Python 3.2, Python 3.3, Python 3.4, Python 3.5
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue17294>
_______________________________________
More information about the New-bugs-announce
mailing list