[Python] Type-hint enclosing class of function in wrapper

Discussão em 'Python' iniciado por Stack, Julho 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm designing an @action decorator as part of an API to collect and expose certain methods on a class to a backend, and I'd like its parameters to dynamically reflect the instance's state. For example:

    class Player():
    ...
    def _private_fun(): ...

    @action(
    param_type_factory = {
    "target": lambda player: Literal[tuple(player.opponents)]
    }
    )
    def attack_action(self, target):
    ...


    Here, player.opponents changes over time, so the type hint for target needs to be updated each time before it gets used by the backend. But static type checks flag player as unknown inside the lambda. Is there a way to type hint the argument passed to the lambda as type=Player, which is the enclosing class? Or better, type hint the factory as

    param_type_factory: Dict[
    str,
    Callable[[<enclosing-class>], Any]
    ]


    so the factory always receives the object instance = an object of the enclosing class the decorated method is in to generate the type hints per param?

    I looked at built-in decorators like @classmethod, but I couldnt get them to work how i wanted.


    If that's not possible, I'm open to redesign patterns, e.g. returning an Action object:

    @action
    def attack_action(self):
    return Action(
    attack,
    param_type_facotry = {
    "target": Tuple[self.opponents]
    }
    )

    def attack(self, target):
    ...


    but it feels verbose to split the metadata from the logic. Any ideas for a more concise, type-safe/type-hinted pattern/decorator?

    Thanks a lot!

    Continue reading...

Compartilhe esta Página