문제

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