[issue43609] ast.unparse-ing a FunctionType gives ambiguous result

Batuhan Taskaya report at bugs.python.org
Fri Mar 26 15:08:50 EDT 2021


Batuhan Taskaya <isidentical at gmail.com> added the comment:

> @BTaskaya I've seen this in third party ides and type checker. For example they are referring to "Union[Callable[[], Union[int, str]], None]" as "() -> (int | str) | None" where there are parentheses around the returns.

Though you can not simple parse this and expect to get the AST you gave as an example (fun2). This would be parsed like
FunctionType(
    argtypes=[],
    returns=BinOp(
        left=BinOp(
            left=Name(id='int', ctx=Load()),
            op=BitOr(),
            right=Name(id='str', ctx=Load())),
        op=BitOr(),
        right=Constant(value=None)))

and we would roundtrip it;
>>> source = '() -> (int | str) | None'
>>> ast1 = ast.parse(source, mode='func_type')
>>> ast2 = ast.parse(ast.unparse(ast1), mode='func_type')
>>> ast.dump(ast1) == ast.dump(ast2)
True


I get what you mean (like 2 separate nodes connected with Union[]) though you can not simply parse the func_type syntax ( () -> ... ) with the normal parser, so you can't use it with binary or. It seems like this is not a bug on ourside, but rather a bug on the creator of this source (like union of func type and binary or).

----------
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43609>
_______________________________________


More information about the Python-bugs-list mailing list