質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top