This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: typing.get_type_hints doesn't really work for classes with ForwardRefs
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6
process
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 2022-04-11 14:58 by admin. 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:

a.py:
class Base:
    a: 'A'

class A:
    pass

b.py:
from a import Base

class MyClass(Base):
    b: 'B'

class B:
    pass


>>> 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()
glob.update(a.__dict__)
glob.update(b.__dict__)

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 https://github.com/python/cpython/commit/f350a268a7071ce7d7a5bb86a9b1229782d4963b on master, and backported to 3.6.
History
Date User Action Args
2022-04-11 14:58:44adminsetgithub: 74152
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