1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to type function which returns associated type so that it works in subclass?

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 09:02.

  1. Stack

    Stack Membro Participativo

    I have a class Foo which has a to_bar method which returns Bar. I also have a subclass MyFoo for which to_bar returns MyBar (a subclass of Bar). Foo has quite a lot of methods which can return Bar, and for each one of these, the corresponding method on MyFoo should return MyBar.

    Here's what I've written:

    from __future__ import annotations

    class Foo:
    def __init__(self, value):
    self.value = value

    @property
    def _bar(self) -> type[Bar]:
    return Bar

    def to_bar(self) -> Bar:
    return self._bar(self.value)

    class Bar:
    def __init__(self, value):
    self.value = value

    class MyFoo(Foo):
    @property
    def _bar(self) -> type[MyBar]:
    return MyBar

    class MyBar(Bar):
    ...

    print(type(Foo(3).to_bar()))
    print(type(MyFoo(3).to_bar()))


    It outputs

    $ python t.py
    <class '__main__.Bar'>
    <class '__main__.MyBar'>


    which is correct. All good so far.

    BUT, if I add

    reveal_type(Foo(3).to_bar())
    reveal_type(MyFoo(3).to_bar())


    to the end of the file and run mypy on it, I get

    $ mypy t.py
    t.py:28: note: Revealed type is "t.Bar"
    t.py:29: note: Revealed type is "t.Bar"
    Success: no issues found in 1 source file


    How can I type to_bar such that the return value is going to be correct for MyFoo.to_bar? I could overwrite to_bar in MyFoo, but doing so for every method which returns Bar in Foo would be tedious and error-prone

    Continue reading...

Compartilhe esta Página