New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
PEP604-style union with python<3.10 after __future__
import
#283
Comments
I was too hasty. You're talking about adding support for |
That parser you wrote made this easy to implement. Thank you! |
Now I'm wondering: could we have done this with just AST manipulation, instead of involving third party dependencies? After all, the problem with PEP 604 is not incompatible syntax, but rather the lack of class-level
|
Here's a 20 min coodle (code-doodle): from ast import (
BinOp, Index, Load, Name, NodeTransformer, Subscript, Tuple, fix_missing_locations,
parse)
from typing import Any, Dict, FrozenSet, List, Set, Union
class UnionTransformer(NodeTransformer):
def visit_BinOp(self, node: BinOp) -> Any:
self.generic_visit(node)
return Subscript(
value=Name(id='Union', ctx=Load()),
slice=Index(
Tuple(elts=[node.left, node.right], ctx=Load()),
ctx=Load()
),
ctx=Load()
)
type_mappings = {"dict": Dict, "list": List, "tuple": Tuple, "set": Set, "frozenset": FrozenSet}
parsed = parse("str | int | dict[str, int]", "<string>", "eval")
UnionTransformer().visit(parsed)
fix_missing_locations(parsed)
code = compile(parsed, "<string>", "eval")
print(eval(code, globals(), type_mappings)) Result when run:
I don't think your parser translates the built-in collection types to their Typing equivalents, but this will (with just a two line change, no less!). |
@supersergiy Would you mind looking at #291? |
Is your feature request related to a problem? Please describe.
We can't use
typeguard
+ PEP604-style union with python <3.10. A good fraction of packages don't state explicit support for 3.10 yet, and having to choose betweentypeguard
and PEP604 is very hard.Example:
Describe the solution you'd like
One way is to translate annotations to pre-PEP604 format before passing them to
get_type_hints
. Here's a quick Lark prototype:Grammar:
The text was updated successfully, but these errors were encountered: