alexmojaki / eval_type_backport

Like `typing._eval_type`, but lets older Python versions use newer typing features.
MIT License
11 stars 2 forks source link

Export a `typing.ForwardRef` subclass #17

Closed bswck closed 6 months ago

bswck commented 7 months ago

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 commented 7 months ago

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 commented 7 months ago

@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 commented 7 months ago

This makes sense, and I think it could easily be combined with something that patches typing.ForwardRef as discussed in https://github.com/alexmojaki/eval_type_backport/issues/11#issuecomment-1892437547 so that backporting can just be 'turned on' and apply everywhere.

bswck commented 7 months ago

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

bswck commented 7 months ago

Yeah, sorry for the mess.