I have a convoluted problem with types that I can´t solve.
Let’s say I have some abstract classes and a generic type equivalent to this
from abc import ABC
from typing import Generic, TypeVar
class Action(ABC):
pass
ActionTypeVar = TypeVar("ActionTypeVar", bound="Action")
class Agent(ABC, Generic[ActionTypeVar]):
actions: tuple[ActionTypeVar, ...]
def get_action() -> ActionTypeVar:
return self.action[0]
This works as intended. But I need is to define a function similar to get_action outside the class(in a different package in fact).
def get_action_outside_class(agent: Agent) -> ActionTypeVar:
return agent.actions[0]
The problem is that here the return type is not precise anymore, since we are outside the scope of the class. I wanted to indicate this is of the same type as the elements of agent.actions.
I have tried referencing the elements of Agent.actions in the return of get_action but I can’t find out a proper way to do it.
>Solution :
You aren’t using Agent generically.
def get_action_outside_class(agent: Agent[ActionTypeVar]) -> ActionTypeVar:
return agent.actions[0]
(Any TypeVar would do; it doesn’t need to be the same one you used when defining Agent.)