This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Albert.Zeyer
Recipients Albert.Zeyer
Date 2013-02-25.13:11:25
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1361797886.48.0.856864897447.issue17294@psf.upfronthosting.co.za>
In-reply-to
Content
`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
History
Date User Action Args
2013-02-25 13:11:26Albert.Zeyersetrecipients: + Albert.Zeyer
2013-02-25 13:11:26Albert.Zeyersetmessageid: <1361797886.48.0.856864897447.issue17294@psf.upfronthosting.co.za>
2013-02-25 13:11:26Albert.Zeyerlinkissue17294 messages
2013-02-25 13:11:25Albert.Zeyercreate