Skip to content

get_type_hints() always raises on forward references #508

Description

@ilevkivskyi

ericvsmith/dataclasses#92 (comment) raised an important question (this existing problem is also mentioned in PEP 563). Currently, get_type_hints will raise a NameError in situations where it might not be the desired behaviour (e.g. if used by a class decorator). For example:

def modify(cls):
    types = get_type_hints(cls)
    # do something with 'cls' and 'types'
    return cls

@modify
class C:
    linked: 'C'

It looks like it will be useful to have an option to keep forward references that are currently undefined. For example:

class C:
    x: 'ClassVar[B]'

assert get_type_hints(C, allow_forward=True) == {'x': ClassVar['B']}

class B:
    ...

assert get_type_hints(C, allow_forward=True) == {'x': ClassVar[B]}

Activity

  1. gvanrossum commented on Dec 4, 2017

    @gvanrossum
    Member
  2. self-assigned this
    on Dec 7, 2017
  3. djrochford commented on Apr 17, 2019

    @djrochford

    I take it this was not easy to fix? I, for one, would be very glad to see this fixed, but I gather that's unlikely to happen soon...

  4. ilevkivskyi commented on Apr 17, 2019

    @ilevkivskyi
    MemberAuthor

    This is not easy, but not too hard either. I just didn't have time for this, sorry.

  5. djrochford commented on Apr 17, 2019

    @djrochford

    Oh, no need to apologise! I commented only in the hope of bumping this slightly higher the priority list, but I'll survive, and life is short.

  6. The-Compiler commented on Apr 16, 2021

    @The-Compiler

    A somewhat related Python bug I've opened about this a couple of weeks ago (before finding this issue): Issue 43463: typing.get_type_hints with TYPE_CHECKING imports / getting hints for single argument - Python tracker

  7. srittau commented on Nov 4, 2021

    @srittau
    Collaborator

    Please report this bug to bugs.python.org if it still exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions