This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author kayhayen
Recipients kayhayen
Date 2018-11-02.08:28:52
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1541147333.05.0.788709270274.issue35143@psf.upfronthosting.co.za>
In-reply-to
Content
Hello,

in trying to know what to put into "__annotations__" at run time, the "from __future__ import annotations" pose a new problem. It is now necessary to "unparse" to ast code that is still there. 

Code to do so, is in C API "_PyAST_ExprAsUnicode", but won't work with the Python level ast objects.

I have a kludge, using "compile" and "exec", to get past that. It's pretty ugly to do it like this, and Nuitka cannot be alone in trying to predict the value of "__annotations__". 

This code is my "ast.unparse" replacement:

def unparse(node):
        _host_node = ast.parse("x:1")

        _host_node.body[0].annotation = node

        r = compile(_host_node, "<annotations>", "exec", 1048576, dont_inherit = True)

        # Using exec here, to compile the ast node tree back to string,
        # there is no accessible "ast.unparse", and this works as a hack
        # to convert our node to a string annotation, pylint: disable=exec-used
        m = {}
        exec(r, m) 

        return m["__annotations__"]['x']

I am caching "_host_node" in the real code.

Having a real "ast.unparse" would be better however. It seems that the building blocks are all there, just not in that form.

Yours,
Kay
History
Date User Action Args
2018-11-02 08:28:53kayhayensetrecipients: + kayhayen
2018-11-02 08:28:53kayhayensetmessageid: <1541147333.05.0.788709270274.issue35143@psf.upfronthosting.co.za>
2018-11-02 08:28:53kayhayenlinkissue35143 messages
2018-11-02 08:28:52kayhayencreate