Unpacking Python's Type Annotations

后端 未结 3 427
终归单人心
终归单人心 2021-01-04 13:52

I\'m trying to generate some JavaScript based on the type annotations I have provided in on some Python functions by using the signature() function in the

3条回答
  •  生来不讨喜
    2021-01-04 14:07

    Take note, this applies to Python 3.5.1

    For Python 3.5.2 take a look at phillip's answer.

    You shouldn't be checking with the identity operator as Phillip stated, use equality to get this right.

    To check if a hint is a subclass of a list you could use issubclass checks (even though you should take note that this can be quirky in certain cases and is currently worked on):

    issubclass(List[int], list)  # True
    

    To get the members of a type hint you generally have two watch out for the cases involved.

    If it has a simple type, as in List[int] the value of the argument is located in the __parameters__ value:

    signature.return_annotation.__parameters__[0] # int
    

    Now, in more complex scenarios i.e a class supplied as an argument with List[User] you must again extract the __parameter__[0] and then get the __forward_arg__. This is because Python wraps the argument in a special ForwardRef class:

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

    Take note, you don't need to actually use inspect here, typing has a helper function named get_type_hints that returns the type hints as a dictionary (it uses the function objects __annotations__ attribute).

提交回复
热议问题