[Python] How to typehint functools.partial classes

Discussão em 'Python' iniciado por Stack, Agosto 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm struggling to type hint correctly a python dataclass (or any class) with partial initialization, it seems that the type is lost somewhere but not sure where:

    from dataclasses import dataclass
    from functools import partial
    @dataclass
    class Test:
    a : int
    b : int

    @classmethod
    def test_partial[T: Test](cls: type[T], b:int) -> partial[T]:
    return partial(cls, b=b)

    @classmethod
    def test_partial2(cls, b:int):
    return partial(cls, b=b)

    part = Test.test_partial(3)
    part( # linter suggest nothing when passing here

    part2 =partial(Test, b=3)
    part2( # linter suggest a=...,b=... when passing

    # interestingly enough letting out the typehint, the linter knows again

    part = Test.test_partial2(3)
    part( # linter suggest a=...,b=... when passing




    The interesting thing is that both mypy and typeright get's it right when I don't give it to them, so probably there is a way. Any clue?

    Continue reading...

Compartilhe esta Página