dropbox / sqlalchemy-stubs

Mypy plugin and stubs for SQLAlchemy
Apache License 2.0
573 stars 101 forks source link

Add one overload to Session.query to type queries of one single item #151

Closed tiangolo closed 4 years ago

tiangolo commented 4 years ago

Add one overload to Session.query() to handle return types for a query of one single item.

This helps with the specific case of querying a single model or column.

For more than one item in the query() it seems that another plugin hook is the only option, as the return is not a plain Tuple but a KeyedTuple.

This is what I found possible continuing the discussion in https://github.com/dropbox/sqlalchemy-stubs/pull/149


I tried playing with the KeyedTuple trying to add overloads or something, but I ended up reading a bunch of issues/discussion in mypy and typing and realizing that Tuple and Callable are the only variadics and that there's currently no way to declare variadic Generic sub-types/sub-classes of Tuple.

One option I considered was creating several generic classes with a fixed amount of type variables in each and making the KeyedTuple a union of all of them, but that wouldn't let using it as a Generic in return types, so I think that doesn't make that much sense.

The other option I considered was trying to hack around with typing._VariadicGenericAlias to try to replicate the variadic-ness of Tuple, given that KeyedTuple is just an extended tuple. But I guess I should avoid touching that as it's a "private" class of typing.

tiangolo commented 4 years ago

Great, thanks! :rocket: