简体   繁体   中英

How to annotate the return type of python function to be exactly the same as one of the arguments?

How to change annotations in the action method below, to make sure that both View and Action are inner classes of the same class inheriting from Table ?

from __future__ import annotations


class Player:
    def action(self, table_view: Table.View) -> Table.Action:
        ...


class Table:
    class View:
        ...

    class Action:
        ...

So for example, if I will make a subclass class LimitTable(Table) and pass instance of LimitTable.View as an argument to action method, I want to make sure the return type will also be LimitTable.Action .

I know I should use typing.TypeVar in some way, but after reading python docs and corresponding PEPs and browsing all questions about it here, I still have no clue how to do it.

The closest you can come is to define a type variable T which is bounded by Table :

T = TypeVar('T', bounded=Table)

and use that in place of Table in your type hints:

class Player:
    def action(self, table_view: T.View) -> T.Action:
        ...

This, however, does not not prevent action from taking a Table.View as an argument and returning a LimitedTable.Action ; this is a known issue, acknowledged in PEP-484 :

Unfortunately, addressing this would require introducing a much more powerful and also much more complicated concept, F-bounded polymorphism. We may revisit this in the future.

The other issue (one I presume you have taken care of, but worth pointing out) is that you still need some way, given an instance of Table.View , to identify the correct Action class for the return type. You don't have an instance of Table available so that you can use something like type(table_view).Action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM