Question

if I try compile some bad python code:

bad_code = """
r
"""

import compiler
print compiler.parse(bad_code)

I get

Module(None, Stmt([Discard(Name('r'))]))

Can I always assume that if I see Discard in the tree, that the code is bad ? Or is it more subtle?

Was it helpful?

Solution

No, Discard is generated for any expression that has its result unused:

>>> compiler.parse("1")
Module(None, Stmt([Discard(Const(1))]))

>>> compiler.parse("def x(): yield 1")
Module(None, Stmt([Function(None, 'x', (), (), 0, None, Stmt([Discard(Yield(Const(1)))]))]))

For example, InteractiveCodeGenerator emits a PRINT_EXPR for Discard nodes, while normal CodeGenerator just POP_TOPs its result away.

Your "bad code" is not bad syntax-wise. Bad code will get you a SyntaxError.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top