[New-bugs-announce] [issue46369] get_type_hints does not evaluate ForwardRefs inside NewType

Andreas H. report at bugs.python.org
Thu Jan 13 16:49:34 EST 2022


New submission from Andreas H. <ahangauer at gmx.net>:

Consider the following: 

    NewT = typing.NewType("NewT", typing.List[typing.Optional['Z']] )

    class Z:
        pass


Now get_type_hints() does not resolve the ForwardRef within NewType (but it does so for TypedDict, dataclasses, NamedTuple).


Neither of the following works.

1)  
    class dummy:
        test: NewT

    get_type_hints(test,None,None)
    
    print( NewT.__supertype__.__args__[0].__args__[0]__.__forward_evaluated__ )
    # --> False
    
Note: investigating the return value of get_type_hints does not change the outcome. 
get_type_hints() patches ForwardRefs in-place.


2) 
    get_type_hints(NewT,None,None)
    # --> TypeError   is not a module, class, method, or function



For Python 3.10+ a workaround exists, but requires access to implementation details of NewType:
  
   class dummy:
       test: NewT.__supertype__
   get_type_hints( dummy, globalns=sys.modules[NewT.__module__].__dict__, localns=None )


Possible solution could be 
 A) to extent `get_type_hints` to explicitly handle NewType (basically call _eval_type for the __supertype__ member).
    That makes approach 2) work (but not 1)
 or B) to extend _eval_type() to handle process NewType as well. This would make 1) work (but not 2).

I guess, since NewType is supposed to be semantically a subclass of the referred type, 2) is probably the preferred approach, which would suggest A). 


Strictly speaking this issue exits in all Python versions that have NewType, but it is easier to fix in 3.10 because there NewType has the __module__ member.

----------
components: Library (Lib)
messages: 410528
nosy: andreash, gvanrossum, kj
priority: normal
severity: normal
status: open
title: get_type_hints does not evaluate ForwardRefs inside NewType
type: behavior
versions: Python 3.10, Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46369>
_______________________________________


More information about the New-bugs-announce mailing list