sqlalchemy2-stubs icon indicating copy to clipboard operation
sqlalchemy2-stubs copied to clipboard

Proper typing for `run_sync` method is now possible

Open michaeloliverx opened this issue 3 years ago • 4 comments

Is your feature request related to a problem? Please describe.

I authored https://github.com/sqlalchemy/sqlalchemy/issues/5777 which added a typevar to run_sync to infer the return value. At that time is was not possible to infer *args or **kwargs of the callable passed and nor was it possible to infer that the first argument of type Session passed automatically for you. Since Python 3.10 has been released we have additional typing constructs typing.ParamSpec and typing.Concatenate, both of which are available on older python versions using the typing_extensions backport.

Describe the solution you'd like

Properly type all of the run_sync methods, something along the lines of the following should do the trick (I haven't set up an environment to test):

if sys.version_info >= (3, 10):
    from typing import Concatenate
    from typing import ParamSpec
else:
    from typing_extensions import Concatenate
    from typing_extensions import ParamSpec

_T = TypeVar("_T")
_P = ParamSpec("_P")

class AsyncSession(
    _AsyncSessionTypingCommon,
    _SessionInTransactionTypingCommon,
):
    ...
    async def run_sync(
        self,
        fn: Callable[Concatenate[Session, _P], _T],
        *arg: _P.args,
        **kw: _P.kwargs,
    ) -> _T: ...

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context

Have a nice day!

michaeloliverx avatar Jan 09 '22 16:01 michaeloliverx

just a heads up that all typing will be inline for SQLAlchemy 2.0 and my current development focus is getting typing ported. the typing / structure will also be very different from sqlalchemy2-stubs as far as fundamentals, although issues like function callers like run_sync() will apply in the same way obviously.

zzzeek avatar Jan 09 '22 16:01 zzzeek

just a heads up that all typing will be inline for SQLAlchemy 2.0 and my current development focus is getting typing ported. the typing / structure will also be very different from sqlalchemy2-stubs as far as fundamentals, although issues like function callers like run_sync() will apply in the same way obviously.

Thanks for the info. I will leave the implementation for now. Is there a ticket to track the inline work?

michaeloliverx avatar Jan 09 '22 16:01 michaeloliverx

yes this is currently at https://github.com/sqlalchemy/sqlalchemy/issues/6810 .

There are also other related issues, I'll try to cross-link them now

zzzeek avatar Jan 09 '22 16:01 zzzeek

I think mypy does not support pep 612 at the moment. We would need to check if id degrades gracefully (ie consider it any/any)

CaselIT avatar Jan 09 '22 21:01 CaselIT