Skip to content
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

Export a typing.ForwardRef subclass #17

Closed
bswck opened this issue Apr 5, 2024 · 5 comments · Fixed by #21
Closed

Export a typing.ForwardRef subclass #17

bswck opened this issue Apr 5, 2024 · 5 comments · Fixed by #21

Comments

@bswck
Copy link
Contributor

bswck commented Apr 5, 2024

A convenient use case for providing a backport-supporting typing.ForwardRef subclass is when "stashing" info about type annotations in a way that allows to evaluate them later (within _eval_direct and not typing.ForwardRef._evaluate, if applicable) with a proper runtime evaluation strategy "smuggled in" implicitly.

Then, in libraries constructing ForwardRef from annotation strings manually, a snippet like this could be used to get the proper implementation of ForwardRef:

try:
    from eval_type_backport import ForwardRef
except ImportError:
    from typing import ForwardRef

...
ann = ForwardRef("type[int] | None")
ann._evaluate(None, None)  # works on 3.8+
@bswck
Copy link
Contributor Author

bswck commented Apr 5, 2024

In case we want to support this in a decent way, we can delegate the actual _eval_direct logic to the eval_type_backport.ForwardRef._evaluate() method, which I consider "the smallest unit" of type annotation evaluation (typing._eval_type is just a wrapper that calls ForwardRef._evaluate()). Then, in eval_type_backport.eval_type_backport(), simply wrap annotation strings with the eval_type_backport.ForwardRef class and call eval_type_backport.ForwardRef._evaluate().

@bswck
Copy link
Contributor Author

bswck commented Apr 5, 2024

@alexmojaki Would you be interested in a quick PR to better show my idea?

I'd find a use case for this in https://github.com/Lucretiel/autocommand and honestly think it will be a very convenient API this library can provide for other libraries.

@alexmojaki
Copy link
Owner

This makes sense, and I think it could easily be combined with something that patches typing.ForwardRef as discussed in #11 (comment) so that backporting can just be 'turned on' and apply everywhere.

@bswck
Copy link
Contributor Author

bswck commented Apr 5, 2024

Great! More than happy to dig out my old idea and make use of it again.

@bswck
Copy link
Contributor Author

bswck commented Apr 16, 2024

Yeah, sorry for the mess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants