Skip to content

How to typehint an attribute of a generic type? #1510

Answered by erictraut
FeryET asked this question in Q&A
Discussion options

You must be logged in to vote

No, that's not possible in the type system today. If there's a specific attribute that you're interested in, you could define a generic protocol class, like this:

Code sample in pyright playground

from typing import Callable, Protocol

class SupportsFoo[T](Protocol):
    """ Structural type for a class that supports a read/write "foo" parameter """
    foo: T

def decorator[**Params, T](func: Callable[Params, SupportsFoo[T]]) -> Callable[Params, T]:
    def wrapper(*args: Params.args, **kwargs: Params.kwargs) -> T:
        return getattr(func(*args, **kwargs), 'foo')
    return wrapper


class FooImpl:
    foo: int

@decorator
def func() -> FooImpl:
    ...

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by FeryET
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants