What's the correct way to check if an object is a typing.Generic?

后端 未结 3 901
你的背包
你的背包 2021-01-01 09:55

I\'m trying to write code that validates type hints, and in order to do so I have to find out what kind of object the annotation is. For example, consider this snippet that\

3条回答
  •  粉色の甜心
    2021-01-01 10:51

    The most you could do, I think, is to use your typ on a variable, use typing.get_type_hints on it and extract the info you need from the returned __annotations__-like dictionary.

    PEP-484 says:

    get_type_hints(), a utility function to retrieve the type hints from a function or method. Given a function or method object, it returns a dict with the same format as __annotations__, but evaluating forward references (which are given as string literals) as expressions in the context of the original function or method definition.

    26.1.7. Classes, functions, and decorators says:

    At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types.

    However, PEP-526 says in 'Non-goals':

    While the proposal is accompanied by an extension of the typing.get_type_hints standard library function for runtime retrieval of annotations, variable annotations are not designed for runtime type checking. Third party packages will have to be developed to implement such functionality.

提交回复
热议问题