Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inferring parameter types and return type of a type[T] #18066

Open
InSyncWithFoo opened this issue Oct 29, 2024 · 0 comments
Open

Inferring parameter types and return type of a type[T] #18066

InSyncWithFoo opened this issue Oct 29, 2024 · 0 comments
Labels

Comments

@InSyncWithFoo
Copy link
Contributor

From this discussion at @microsoft/pyright:

(playground)

@dataclass(kw_only = True)
class User:
    id: int
    name: str

class HasCls[**P, T](Protocol):
    cls: Callable[P, T]

class Repository[T]:
    cls: type[T]

    def __init__(self, cls: type[T]) -> None: ...
    def create[**P](self: HasCls[P, T], *args: P.args, **kwargs: P.kwargs) -> T: ...

class UserDatabase(Repository[User]):
    def __init__(self) -> None: ...

Expected:

user = UserDatabase().create(id = 1, name = 'foo')  # fine

reveal_type(UserDatabase().create)  # (*, id: int, name: str) -> User
reveal_type(user)                   # User

Actual:

# error: Invalid self argument "UserDatabase" to attribute function "create" with type "Callable[[HasCls[P, T], **P], T]" [misc]
user = UserDatabase().create(id = 1, name = 'foo')

reveal_type(UserDatabase().create)  # (*args: Never, **kwargs: Never) -> User
reveal_type(user)                   # User

The pattern above is supported by Pyright, if not for a bug that this snippet helped discovering (which has since been fixed).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant