Title: typing.get_type_hints doesn't really work for classes with ForwardRefs
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: levkivskyi, simon.percivall
Priority: normal Keywords:

Created on 2017-04-03 10:21 by simon.percivall, last changed 2017-09-15 16:27 by levkivskyi. This issue is now closed.

Messages (4)
msg291058 - (view) Author: Simon Percivall (simon.percivall) Date: 2017-04-03 10:21
For classes with ForwardRef annotations, typing.get_type_hints is unusable.

As example, we have two files:
class Base:
    a: 'A'

class A:
from a import Base

class MyClass(Base):
    b: 'B'

class B:

>>> from typing import get_type_hints
>>> from b import MyClass
>>> get_type_hints(MyClass) #  NameError

What should globals/locals be here?
msg291139 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2017-04-04 20:29
You could try:

glob = globals.copy()

You can do this automatically following MyClass.__mro__ and then collecting relevant __module__ attributes on bases.

However, there is little chance this will be fixed in typing itself. It is difficult to cover all possible cases, so that users should choose custom globals/locals for their needs.
msg291517 - (view) Author: Simon Percivall (simon.percivall) Date: 2017-04-11 21:23
It think it's important to document this caveat in `get_type_hints`, that there is virtually _no_ way to use it safely with a class, and that there will always be a high risk of getting an exception unless using this function in a highly controlled setting.

This also, as a consequence, means that there is no "best-effort" support for collecting type hints from a class hierarchy, and every instance of trying to use this function with classes, or traversing __annotations__ "manually", will need to be solved ad-hoc and from scratch by the user (until someone publishes a "typing-utils" package on PyPI).
msg302264 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2017-09-15 16:27
This is now fixed (to a reasonable extent) by on master, and backported to 3.6.
Date User Action Args
2017-09-15 16:27:36levkivskyisetstatus: open -> closed
resolution: fixed
messages: + msg302264

stage: resolved
2017-04-11 21:23:34simon.percivallsetmessages: + msg291517
2017-04-04 20:29:56levkivskyisetnosy: + levkivskyi
messages: + msg291139
2017-04-03 10:36:46Jim Fasarakis-Hilliardsettype: behavior
components: + Library (Lib)
2017-04-03 10:21:14simon.percivallcreate