Skip to content

Instantly share code, notes, and snippets.

@dibrinsofor
Created September 12, 2025 19:24
Show Gist options
  • Select an option

  • Save dibrinsofor/791543dceeba72c93d1db3f71f64e527 to your computer and use it in GitHub Desktop.

Select an option

Save dibrinsofor/791543dceeba72c93d1db3f71f64e527 to your computer and use it in GitHub Desktop.
[mypy]
plugins = myplug.py
from mypy.plugin import Plugin, FunctionContext
from mypy.subtypes import is_subtype
from mypy.types import AnyType, LiteralType
from typing import Any
class Special(AnyType):
def __repr__(self) -> str:
return "Special Subtype Type"
class MyPlugin(Plugin):
def get_function_hook(self, fullname: str) -> Any:
if "check_sub" in fullname:
return self.fn_hook
return None
def fn_hook(self, ctx: FunctionContext) -> Any:
if len(ctx.arg_types) == 2:
t1, t2 = ctx.arg_types[0][0], ctx.arg_types[1][0]
str_type = ctx.api.named_generic_type("builtins.str", [])
if is_subtype(t1, t2):
return LiteralType(value="YES", fallback=str_type)
else:
return LiteralType(value="NO", fallback=str_type)
return ctx.default_return_type
def plugin(version: str) -> type[MyPlugin]:
return MyPlugin
from typing import reveal_type
class A: ...
class B(A): ...
class C(B): ...
def check_sub(x, y): ...
def f() -> None:
reveal_type(check_sub(B(), A())) # plugin sees B <: A
reveal_type(check_sub(C(), A())) # plugin sees C <: A
reveal_type(check_sub(A(), B())) # not a subtype
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment