On Thu, 16 Jul 2020 at 15:24, Guido van Rossum <guido@python.org> wrote:
On Thu, Jul 16, 2020 at 07:21 Patrick Arminio <patrick.arminio@gmail.com> wrote:
On Thu, 16 Jul 2020 at 15:17, Guido van Rossum <guido@python.org> wrote:
Perhaps you can pass the locals dict to get_type_hints()?
locals would probably the right options, but unfortunately I don't have access to the locals where the type was defined, as I'd need to call get_type_hints from another function.
Maybe I'm missing something obvious?
Looks like you have to change your protocol. Why are those classes hidden inside a function instead of living in a module?
Mainly because I'm writing them in tests. I guess I could "force" users of the library to not do something like that, as it is a very specific use case (I can't think of anything else other than tests for something like this). So, I'm guess the only solution would be to move the classes outside the tests and import the module dynamically, when dealing with ForwardRefs, like I did here? [...snip] def get_first_field_type(type: Type) -> Type: field = dataclasses.fields(type)[0] field_type = field.type # one option would be to use something like this, but it would # only work when the type was declared in the module namespace # and also might introduce side effects if the imported module # runs code at import time # def resolve_hint(hint): # def f(x: field_type): pass # namespace = importlib.import_module(type.__module__).__dict__ # return get_type_hints(f, None, namespace)['x'] -- Patrick Arminio