New submission from Andreas H. <ahanga...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue46369>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to