GOAL I am trying to compile an AST which contains an ImportFrom node which performs a __future__ import. The ImportFrom node in question is the first node within the AST's body (as it should be, because __future__ imports must occur at the beginning of modules). ISSUE Compiling the AST fails with the error "SyntaxError: from __future__ imports must occur at the beginning of the file". ANALYSIS The future_parse() function in future.c looks for __future__ imports and identifies them based on the condition (ds->v.ImportFrom.module == future) where future is constructed using PyString_InternFromString("__future__"). That is, the module attribute of the ImportFrom node is compared by identity with the interned string "__future__". The AST which I was compiling used the string "__future__" after extracting that string from a much longer string of user input, and as a result, the string was not interned. The attached file futureimport.py is a simple script demonstrating this issue. I have confirmed that the issue occurs in Python 2.7.2 and 3.2.2.
Incidentally, the workaround that I'm using for the time being is to run the following code before attempting to compile root_node. for node in ast.walk(root_node): if isinstance(node, ast.ImportFrom) and node.module == '__future__': node.module = '__future__'