Perhaps you can pass the locals dict to get_type_hints()?

https://docs.python.org/3/library/typing.html#typing.get_type_hints

On Thu, Jul 16, 2020 at 06:52 Patrick Arminio <patrick.arminio@gmail.com> wrote:
Hi folks, I'm working on a library that makes extensive of use of type hints at runtime and I found this use case where I need to
evaluate a forward reference

```python
def test_forward_references():

  @dataclasses.dataclass
  class User:
      username: str

  @dataclasses.dataclass
  class Product:
      reviews: List["Review"]

  @dataclasses.dataclass
  class Review:
      text: str
```

as youy can see List["Review"] has a reference to the not yet declared class Review.
My use case is to generate class based on the type hints of these 3 classes, unfortunately
when I try to inspect the field type of Product.reviews, I get List[ForwardRef("Review)]
and I'm not sure how I could get the actual type at run time.

I've made a repl that shows what I've tried so far: https://repl.it/@patrick91/dcth-2

I've tried getting the global namespace for the module, but that won't work in this case, since
the classes are defined inside a function.

I have another option, which is to store all the decorated classes in a global dict (I'm using a different decorator that the dataclasses one),
but I don't want to do that as my users could register multiple types with the same name.

Any ideas on how I could solve this?
_______________________________________________
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
https://mail.python.org/mailman3/lists/typing-sig.python.org/
Member address: guido@python.org
--
--Guido (mobile)