[Python] TypeError: Invalid annotation for 'value'. typing.Type[bool] is not a class

Discussão em 'Python' iniciado por Stack, Novembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    In Python 3.8 a new decorator for creating polymorphic functions was created, @singledispatch, which redirects Python to the correct implementation of your method depending on the type hints provided.

    from datetime import datetime
    from functools import singledispatch
    from random import choice, randint
    from typing import NoReturn, Type


    @singledispatch
    def load_value(value) -> NoReturn:
    raise NotImplementedError(f'Unsupported type: {value}')


    @load_value.register
    def _(value: Type[bool]) -> bool:
    return choice([False, True])


    @load_value.register
    def _(value: Type[int]) -> int:
    return randint(0, 1000)


    @load_value.register
    def _(value: Type[datetime]) -> datetime:
    return datetime.now()


    print(load_value(bool))
    print(load_value(int))
    print(load_value(datetime))


    However, I don't seem to be able to use types as arguments; please could you tell me what is wrong with my example? How should I annotate a parameter so that it is recognized as a type?

    $ python ./register.py
    Traceback (most recent call last):
    File "./register.py", line 40, in <module>
    def _(value: Type[bool]) -> bool:
    File "/app/pyenv/versions/3.8.11/lib/python3.8/functools.py", line 860, in register
    raise TypeError(
    TypeError: Invalid annotation for 'value'. typing.Type[bool] is not a class.


    The corresponding function must be called depending on the class passed as an argument.

    Continue reading...

Compartilhe esta Página