Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

type hint for generic attribute inside abstract class

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading