Search code examples
pythonabstract-syntax-tree

Python AST code sample taken from the book Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More


I'm reading the book Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More from Julien Danjou and I'm having trouble from a code got from chapter 8. This is the code:

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)

And It's giving for me the follow error:

code = compile(module, '', 'exec')
TypeError: required field "type_ignores" missing from Module

I double check if I was typing something wrong but I didn't find anything wrong.

Can someone give me a clue, please?

Thank you very much!


Solution

  • This error and how to fix it is explained in this issue: There were changes in the python ast module, probably after the book came out, ast.Module now expects you to pass a list called type_ignores. For your purposes, you can just pass an empty list:

    module = ast.Module(
        body=[ast.Expr(print_call, lineno=1, col_offset=1)],
        lineno=1,
        col_offset=1,
        type_ignores=[],
    )
    

    full working code example here.