Unpacking Python Annotations

I am trying to create some JavaScript based on the type annotations that I provided in some Python functions using a function signature()in a module inspect.

This part works as I expect when a type is a simple inline class:

import inspect

def my_function() -> dict:
    pass

signature = inspect.signature(my_function)
signature.return_annotation is dict  # True

Although I'm not sure how to expand and check for more complex annotations, for example:

from typing import List
import inspect

def my_function() -> List[int]:
    pass

signature = inspect.signature(my_function)
signature.return_annotation is List[int]  # False

Again a similar problem with a direct reference to a custom class:

def my_function() -> List['User']:
    pass
...
signature.return_annotation  # typing.List[_ForwardRef('User')]

What I'm going to get out is something like this - so that I can come up correctly when creating JavaScript:

type = signature.return_annotation... # list
member_type = signature.return_annotation... # int / 'User'

Thank.

+4
source share
2 answers

List GenericMeta, . :

>>> [ id(List[str]) for i in range(3) ]
[33105112, 33106872, 33046936]

, List[int] is not List[int]. , :

  • ==, .. signature.return_annotation == List[int].
  • ,

    a = List[int]
    def foo() -> a:
        pass
    inspect.signature(foo).return_annotation is a
    
  • issubclass. . , , , _TypeAlias, .

  • List . , , : List[int].__args__[0] , Python 3.5.2, - List[int].__parameters__[0].

, , , . , ==.

+1

, Python 3.5.1

Python 3.5.2 phillip.

, , , .

, list, issubclass ( , ):

issubclass(List[int], list)  # True

, .

, List[int], __parameters__:

signature.return_annotation.__parameters__[0] # int

, , , List[User], __parameter__[0], __forward_arg__. , Python ForwardRef:

d = signature.return_annotation.__parameter__[0]
d.__forward_arg__ # 'User'

: inspect, typing get_type_hints, ( object objects __annotations__).

+2

Source: https://habr.com/ru/post/1649809/


All Articles