Python AST 代码示例取自 Serious Python:关于部署、可扩展性、测试等方面的黑带建议
Python AST code sample taken from the book Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More
我正在阅读 Julien Danjou 的《Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More》这本书,我在第 8 章的代码中遇到了麻烦。
这是代码:
import ast
hello_world = ast.Str(s = 'hello world!', lineno=1, col_offset=1)
print_name = ast.Name(id='print', ctx=ast.Load(), lineno=1, col_offset=1)
print_call = ast.Call(func=print_name, ctx=ast.Load(), args=[hello_world], keywords=[], lineno=1, col_offset=1)
module = ast.Module(body=[ast.Expr(print_call, lineno=1, col_offset=1)], lineno=1, col_offset=1)
code = compile(module, '', 'exec')
eval(code)
它给我以下错误:
code = compile(module, '', 'exec')
TypeError: required field "type_ignores" missing from Module
我仔细检查了我是否输入了错误,但我没有发现任何错误。
有人可以给我线索吗?
非常感谢!
解释了这个错误以及如何修复它 in this issue: python ast 模块发生了变化,可能是在本书出版后,ast.Module
现在希望你通过名为 type_ignores
的列表。为了您的目的,您可以只传递一个空列表:
module = ast.Module(
body=[ast.Expr(print_call, lineno=1, col_offset=1)],
lineno=1,
col_offset=1,
type_ignores=[],
)
我正在阅读 Julien Danjou 的《Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More》这本书,我在第 8 章的代码中遇到了麻烦。 这是代码:
import ast
hello_world = ast.Str(s = 'hello world!', lineno=1, col_offset=1)
print_name = ast.Name(id='print', ctx=ast.Load(), lineno=1, col_offset=1)
print_call = ast.Call(func=print_name, ctx=ast.Load(), args=[hello_world], keywords=[], lineno=1, col_offset=1)
module = ast.Module(body=[ast.Expr(print_call, lineno=1, col_offset=1)], lineno=1, col_offset=1)
code = compile(module, '', 'exec')
eval(code)
它给我以下错误:
code = compile(module, '', 'exec')
TypeError: required field "type_ignores" missing from Module
我仔细检查了我是否输入了错误,但我没有发现任何错误。
有人可以给我线索吗?
非常感谢!
解释了这个错误以及如何修复它 in this issue: python ast 模块发生了变化,可能是在本书出版后,ast.Module
现在希望你通过名为 type_ignores
的列表。为了您的目的,您可以只传递一个空列表:
module = ast.Module(
body=[ast.Expr(print_call, lineno=1, col_offset=1)],
lineno=1,
col_offset=1,
type_ignores=[],
)