File: magic_method.py

package info (click to toggle)
mypy 1.19.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,412 kB
  • sloc: python: 114,754; ansic: 13,343; cpp: 11,380; makefile: 257; sh: 28
file content (24 lines) | stat: -rw-r--r-- 851 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
from mypy.types import LiteralType, AnyType, TypeOfAny, Type
from mypy.plugin import Plugin, MethodContext
from typing import Callable, Optional

# If radd exists, there shouldn't be an error. If it doesn't exist, then there will be an error
def type_add(ctx: MethodContext) -> Type:
    ctx.api.fail("fail", ctx.context)
    return AnyType(TypeOfAny.from_error)

def type_radd(ctx: MethodContext) -> Type:
    return LiteralType(7, fallback=ctx.api.named_generic_type('builtins.int', []))


class TestPlugin(Plugin):

    def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]:
        if fullname == 'builtins.int.__add__':
            return type_add
        if fullname == 'builtins.int.__radd__':
            return type_radd
        return None

def plugin(version: str) -> type[TestPlugin]:
    return TestPlugin