[Python] How to specify generic python signature to return type, as well as use type in...

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a function which takes a class as an argument, returns an instance of that class wrapped in another type, and uses the type of the class for casting internally, it works with a simple type like str, but not an actual class.

    I've reduced this code to the point that it's a bit silly to be using generics but it demonstrates my problem at least.

    from typing import cast, Type, TypeVar, Generic, Optional, Any
    from pydantic import BaseModel, UUID4
    from typing_extensions import Annotated, TypeAliasType
    from pydantic.functional_validators import BeforeValidator
    from uuid import UUID

    def api_fn(output_cls: Optional[Type[BaseModel]] = None):
    return None # simplified for example code, signature cannot be changed, not my code

    def amount_f(v: Any) -> float:
    return 0.0 # simplified for example code

    MyNumber = Annotated[float, BeforeValidator(amount_f)]

    DataT = TypeVar('DataT')
    class TypeWithId(BaseModel, Generic[DataT]):
    value: DataT
    id: UUID4

    T = TypeVar('T')
    OptionalWithId = TypeAliasType(
    'OptionalWithId', Optional[TypeWithId[T]], type_params=(T,)
    )

    OutT = TypeVar('OutT')
    def query(output_cls:Type[OutT]) -> OptionalWithId[OutT]:
    ret = api_fn(output_cls=output_cls)
    return TypeWithId(value=cast(OutT,ret), id=UUID('00000000-0000-0000-0000-000000000000'))

    str_result = query(str)
    print(str_result)
    number_result = query(MyNumber)
    print(number_result)


    The str_result works but the number_result gives me:

    27 26 error e-f-b Pyright [reportArgumentType]: Argument of type "type[OutT@query]" cannot be assigned to parameter "output_cls" of type "type[BaseModel] | None" in function "api_fn"
    32 0 error e-f-b Pyright [reportUnknownVariableType]: Type of "number_result" is partially unknown
    32 22 error e-f-b Pyright [reportArgumentType]: Argument of type "MyNumber" cannot be assigned to parameter "output_cls" of type "type[OutT@query]" in function "query"
    33 6 error e-f-b Pyright [reportUnknownArgumentType]: Argument type is partially unknown

    Continue reading...

Compartilhe esta Página