Q: How to generate code object from bytecode?

Carsten Haese carsten at uniqsys.com
Tue Dec 26 15:06:16 EST 2006


On Tue, 2006-12-26 at 14:48 -0500, Carsten Haese wrote:
> * Code objects come in two flavors: statements and expressions.
> * exec can execute a 'statement' flavored code object.
> * eval can evaluate an 'expression' flavored code object.
> * Your code snippet is a statement, actually, a suite of statements. You
> need to exec it, not eval it.

And to reply to myself before the effbot corrects me, it turns out that
the separation between expressions and statements is not quite so
strict. For one, an expression can be used like a statement.

Also, apparently eval() can evaluate the code object of a statement,
even though it can't evaluate the source code of a statement, which I
find oddly inconsistent:

>>> eval("print 'Hi'")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    print 'Hi'
        ^
SyntaxError: invalid syntax
>>> eval(compile("print 'Hi'", "<script>", "exec"))
Hi

There's probably a deeper reason here, but I don't often write code that
needs to rely on eval/exec, so I don't really care ;)

-Carsten





More information about the Python-list mailing list