File: typing.py

package info (click to toggle)
python-duet 0.2.9-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 236 kB
  • sloc: python: 1,423; sh: 30; makefile: 7
file content (82 lines) | stat: -rw-r--r-- 3,297 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Copyright 2021 The Duet Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Mypy plugin to provide better typechecking of duet functions.

For more information about mypy plugins see:
https://mypy.readthedocs.io/en/stable/extending_mypy.html#extending-mypy-using-plugins
"""

from typing import Callable, List, Optional

from mypy.plugin import FunctionContext, Plugin
from mypy.types import CallableType, get_proper_type, Instance, Overloaded, Type


def duet_sync_callback(ctx: FunctionContext) -> Type:
    """Callback to provide an accurate signature for duet.sync.

    The duet.sync function wraps an async callable in a synchronous wrapper:

        def sync(f: Callable[..., Awaitable[T]]) -> Callable[..., T]:

    This plugin basically tells mypy that the two ellipses are exactly the same,
    that is, that the new synchronous callable accepts exactly the same args as
    the original function. This allows for precise typechecking of calls to
    functions wrapped by duet.sync.
    """
    func_type = get_proper_type(ctx.arg_types[0][0])
    if not isinstance(func_type, (CallableType, Overloaded)):
        ctx.api.msg.fail(f"expected Callable[..., Awaitable[T]], got {func_type}", ctx.context)
        return ctx.default_return_type

    if isinstance(func_type, CallableType):
        return modify_callable(func_type, ctx)

    # func_type is overloaded
    overloaded_callables: List[CallableType] = []
    for ft in func_type.items:
        overload_type = modify_callable(ft, ctx)
        if not isinstance(overload_type, CallableType):
            ctx.api.msg.fail(
                f"expected overloaded type to be callable, got {overload_type}", ctx.context
            )
            return ctx.default_return_type
        overloaded_callables.append(overload_type)
    return Overloaded(overloaded_callables)


def modify_callable(func_type: CallableType, ctx: FunctionContext) -> Type:
    # Note that the return type of an async function is Coroutine[Any, Any, T],
    # which is a subtype of Awaitable[T]. See:
    # https://mypy.readthedocs.io/en/stable/more_types.html#typing-async-await
    ret_type = get_proper_type(func_type.ret_type)
    if not (isinstance(ret_type, Instance) and ret_type.type.name == "Coroutine"):
        if not func_type.implicit:
            ctx.api.msg.fail(f"expected return type Awaitable[T], got {ret_type}", ctx.context)
        return ctx.default_return_type

    result_type = ret_type.args[-1]
    return func_type.copy_modified(ret_type=result_type)


class DuetPlugin(Plugin):
    def get_function_hook(self, fullname: str) -> Optional[Callable[[FunctionContext], Type]]:
        if fullname == "duet.api.sync":
            return duet_sync_callback
        return None


def plugin(version: str):
    return DuetPlugin