Skip to content

Add type annotations to test-data/unit/plugins #16028

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mypy/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def fail(

@abstractmethod
def named_generic_type(self, name: str, args: list[Type]) -> Instance:
"""Construct an instance of a builtin type with given type arguments."""
"""Construct an instance of a generic type with given type arguments."""
raise NotImplementedError

@abstractmethod
Expand Down
8 changes: 5 additions & 3 deletions test-data/unit/plugins/add_classmethod.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Callable, Optional
from __future__ import annotations

from typing import Callable

from mypy.nodes import ARG_POS, Argument, Var
from mypy.plugin import ClassDefContext, Plugin
Expand All @@ -7,7 +9,7 @@


class ClassMethodPlugin(Plugin):
def get_base_class_hook(self, fullname: str) -> Optional[Callable[[ClassDefContext], None]]:
def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
Copy link
Contributor

@ikonst ikonst Sep 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Speaking of this change - I've just enabled ruff's "pyupgrade" (#16023) which should keep enforcing this, maybe change pyproject.toml to include the plugins in ruff?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will in later PRs, because right now - I don't know how to force ruff to include a subdirectory. Docs do not say much, so I will have to dig into the source code :)

if "BaseAddMethod" in fullname:
return add_extra_methods_hook
return None
Expand All @@ -24,5 +26,5 @@ def add_extra_methods_hook(ctx: ClassDefContext) -> None:
)


def plugin(version):
def plugin(version: str) -> type[ClassMethodPlugin]:
return ClassMethodPlugin
19 changes: 10 additions & 9 deletions test-data/unit/plugins/arg_kinds.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
from typing import Optional, Callable
from mypy.plugin import Plugin, MethodContext, FunctionContext
from __future__ import annotations

from typing import Callable

from mypy.plugin import FunctionContext, MethodContext, Plugin
from mypy.types import Type


class ArgKindsPlugin(Plugin):
def get_function_hook(self, fullname: str
) -> Optional[Callable[[FunctionContext], Type]]:
if 'func' in fullname:
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if "func" in fullname:
return extract_arg_kinds_from_function
return None

def get_method_hook(self, fullname: str
) -> Optional[Callable[[MethodContext], Type]]:
if 'Class.method' in fullname:
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
if "Class.method" in fullname:
return extract_arg_kinds_from_method
return None

Expand All @@ -27,5 +28,5 @@ def extract_arg_kinds_from_method(ctx: MethodContext) -> Type:
return ctx.default_return_type


def plugin(version):
def plugin(version: str) -> type[ArgKindsPlugin]:
return ArgKindsPlugin
48 changes: 32 additions & 16 deletions test-data/unit/plugins/arg_names.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,51 @@
from typing import Optional, Callable
from __future__ import annotations

from mypy.plugin import Plugin, MethodContext, FunctionContext
from typing import Callable

from mypy.nodes import StrExpr
from mypy.plugin import FunctionContext, MethodContext, Plugin
from mypy.types import Type


class ArgNamesPlugin(Plugin):
def get_function_hook(self, fullname: str
) -> Optional[Callable[[FunctionContext], Type]]:
if fullname in {'mod.func', 'mod.func_unfilled', 'mod.func_star_expr',
'mod.ClassInit', 'mod.Outer.NestedClassInit'}:
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if fullname in {
"mod.func",
"mod.func_unfilled",
"mod.func_star_expr",
"mod.ClassInit",
"mod.Outer.NestedClassInit",
}:
return extract_classname_and_set_as_return_type_function
return None

def get_method_hook(self, fullname: str
) -> Optional[Callable[[MethodContext], Type]]:
if fullname in {'mod.Class.method', 'mod.Class.myclassmethod', 'mod.Class.mystaticmethod',
'mod.ClassUnfilled.method', 'mod.ClassStarExpr.method',
'mod.ClassChild.method', 'mod.ClassChild.myclassmethod'}:
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
if fullname in {
"mod.Class.method",
"mod.Class.myclassmethod",
"mod.Class.mystaticmethod",
"mod.ClassUnfilled.method",
"mod.ClassStarExpr.method",
"mod.ClassChild.method",
"mod.ClassChild.myclassmethod",
}:
return extract_classname_and_set_as_return_type_method
return None


def extract_classname_and_set_as_return_type_function(ctx: FunctionContext) -> Type:
classname = ctx.args[ctx.callee_arg_names.index('classname')][0].value
return ctx.api.named_generic_type(classname, [])
arg = ctx.args[ctx.callee_arg_names.index("classname")][0]
if not isinstance(arg, StrExpr):
return ctx.default_return_type
return ctx.api.named_generic_type(arg.value, [])


def extract_classname_and_set_as_return_type_method(ctx: MethodContext) -> Type:
classname = ctx.args[ctx.callee_arg_names.index('classname')][0].value
return ctx.api.named_generic_type(classname, [])
arg = ctx.args[ctx.callee_arg_names.index("classname")][0]
if not isinstance(arg, StrExpr):
return ctx.default_return_type
return ctx.api.named_generic_type(arg.value, [])


def plugin(version):
def plugin(version: str) -> type[ArgNamesPlugin]:
return ArgNamesPlugin
14 changes: 8 additions & 6 deletions test-data/unit/plugins/attrhook.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from typing import Optional, Callable
from __future__ import annotations

from mypy.plugin import Plugin, AttributeContext
from mypy.types import Type, Instance
from typing import Callable

from mypy.plugin import AttributeContext, Plugin
from mypy.types import Instance, Type


class AttrPlugin(Plugin):
def get_attribute_hook(self, fullname: str) -> Optional[Callable[[AttributeContext], Type]]:
if fullname == 'm.Signal.__call__':
def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
if fullname == "m.Signal.__call__":
return signal_call_callback
return None

Expand All @@ -17,5 +19,5 @@ def signal_call_callback(ctx: AttributeContext) -> Type:
return ctx.default_attr_type


def plugin(version):
def plugin(version: str) -> type[AttrPlugin]:
return AttrPlugin
16 changes: 9 additions & 7 deletions test-data/unit/plugins/attrhook2.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from typing import Optional, Callable
from __future__ import annotations

from mypy.plugin import Plugin, AttributeContext
from mypy.types import Type, AnyType, TypeOfAny
from typing import Callable

from mypy.plugin import AttributeContext, Plugin
from mypy.types import AnyType, Type, TypeOfAny


class AttrPlugin(Plugin):
def get_attribute_hook(self, fullname: str) -> Optional[Callable[[AttributeContext], Type]]:
if fullname == 'm.Magic.magic_field':
def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
if fullname == "m.Magic.magic_field":
return magic_field_callback
if fullname == 'm.Magic.nonexistent_field':
if fullname == "m.Magic.nonexistent_field":
return nonexistent_field_callback
return None

Expand All @@ -22,5 +24,5 @@ def nonexistent_field_callback(ctx: AttributeContext) -> Type:
return AnyType(TypeOfAny.from_error)


def plugin(version):
def plugin(version: str) -> type[AttrPlugin]:
return AttrPlugin
2 changes: 1 addition & 1 deletion test-data/unit/plugins/badreturn.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
def plugin(version):
def plugin(version: str) -> None:
pass
6 changes: 5 additions & 1 deletion test-data/unit/plugins/badreturn2.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from __future__ import annotations


class MyPlugin:
pass

def plugin(version):

def plugin(version: str) -> type[MyPlugin]:
return MyPlugin
19 changes: 13 additions & 6 deletions test-data/unit/plugins/callable_instance.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
from __future__ import annotations

from typing import Callable

from mypy.plugin import MethodContext, Plugin
from mypy.types import Instance, Type


class CallableInstancePlugin(Plugin):
def get_function_hook(self, fullname):
assert not fullname.endswith(' of Foo')
def get_function_hook(self, fullname: str) -> None:
assert not fullname.endswith(" of Foo")

def get_method_hook(self, fullname):
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
# Ensure that all names are fully qualified
assert not fullname.endswith(' of Foo')
assert not fullname.endswith(" of Foo")

if fullname == '__main__.Class.__call__':
if fullname == "__main__.Class.__call__":
return my_hook

return None


def my_hook(ctx: MethodContext) -> Type:
if isinstance(ctx.type, Instance) and len(ctx.type.args) == 1:
return ctx.type.args[0]
return ctx.default_return_type

def plugin(version):

def plugin(version: str) -> type[CallableInstancePlugin]:
return CallableInstancePlugin
15 changes: 9 additions & 6 deletions test-data/unit/plugins/class_attr_hook.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
from typing import Callable, Optional
from __future__ import annotations

from typing import Callable

from mypy.plugin import AttributeContext, Plugin
from mypy.types import Type as MypyType


class ClassAttrPlugin(Plugin):
def get_class_attribute_hook(self, fullname: str
) -> Optional[Callable[[AttributeContext], MypyType]]:
if fullname == '__main__.Cls.attr':
def get_class_attribute_hook(
self, fullname: str
) -> Callable[[AttributeContext], MypyType] | None:
if fullname == "__main__.Cls.attr":
return my_hook
return None


def my_hook(ctx: AttributeContext) -> MypyType:
return ctx.api.named_generic_type('builtins.int', [])
return ctx.api.named_generic_type("builtins.int", [])


def plugin(_version: str):
def plugin(_version: str) -> type[ClassAttrPlugin]:
return ClassAttrPlugin
41 changes: 26 additions & 15 deletions test-data/unit/plugins/class_callable.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
from mypy.plugin import Plugin
from __future__ import annotations

from typing import Callable

from mypy.nodes import NameExpr
from mypy.types import UnionType, NoneType, Instance
from mypy.plugin import FunctionContext, Plugin
from mypy.types import Instance, NoneType, Type, UnionType, get_proper_type


class AttrPlugin(Plugin):
def get_function_hook(self, fullname):
if fullname.startswith('mod.Attr'):
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if fullname.startswith("mod.Attr"):
return attr_hook
return None

def attr_hook(ctx):
assert isinstance(ctx.default_return_type, Instance)
if ctx.default_return_type.type.fullname == 'mod.Attr':
attr_base = ctx.default_return_type

def attr_hook(ctx: FunctionContext) -> Type:
default = get_proper_type(ctx.default_return_type)
assert isinstance(default, Instance)
if default.type.fullname == "mod.Attr":
attr_base = default
else:
attr_base = None
for base in ctx.default_return_type.type.bases:
if base.type.fullname == 'mod.Attr':
for base in default.type.bases:
if base.type.fullname == "mod.Attr":
attr_base = base
break
assert attr_base is not None
last_arg_exprs = ctx.args[-1]
if any(isinstance(expr, NameExpr) and expr.name == 'True' for expr in last_arg_exprs):
if any(isinstance(expr, NameExpr) and expr.name == "True" for expr in last_arg_exprs):
return attr_base
assert len(attr_base.args) == 1
arg_type = attr_base.args[0]
return Instance(attr_base.type, [UnionType([arg_type, NoneType()])],
line=ctx.default_return_type.line,
column=ctx.default_return_type.column)
return Instance(
attr_base.type,
[UnionType([arg_type, NoneType()])],
line=default.line,
column=default.column,
)


def plugin(version):
def plugin(version: str) -> type[AttrPlugin]:
return AttrPlugin
36 changes: 20 additions & 16 deletions test-data/unit/plugins/common_api_incremental.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,48 @@
from mypy.plugin import Plugin
from mypy.nodes import (
ClassDef, Block, TypeInfo, SymbolTable, SymbolTableNode, MDEF, GDEF, Var
)
from __future__ import annotations

from typing import Callable

from mypy.nodes import GDEF, MDEF, Block, ClassDef, SymbolTable, SymbolTableNode, TypeInfo, Var
from mypy.plugin import ClassDefContext, DynamicClassDefContext, Plugin


class DynPlugin(Plugin):
def get_dynamic_class_hook(self, fullname):
if fullname == 'lib.declarative_base':
def get_dynamic_class_hook(
self, fullname: str
) -> Callable[[DynamicClassDefContext], None] | None:
if fullname == "lib.declarative_base":
return add_info_hook
return None

def get_base_class_hook(self, fullname: str):
def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
sym = self.lookup_fully_qualified(fullname)
if sym and isinstance(sym.node, TypeInfo):
if sym.node.metadata.get('magic'):
if sym.node.metadata.get("magic"):
return add_magic_hook
return None


def add_info_hook(ctx) -> None:
def add_info_hook(ctx: DynamicClassDefContext) -> None:
class_def = ClassDef(ctx.name, Block([]))
class_def.fullname = ctx.api.qualified_name(ctx.name)

info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)
class_def.info = info
obj = ctx.api.named_type('builtins.object')
obj = ctx.api.named_type("builtins.object", [])
info.mro = [info, obj.type]
info.bases = [obj]
ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
info.metadata['magic'] = True
info.metadata["magic"] = {"value": True}


def add_magic_hook(ctx) -> None:
def add_magic_hook(ctx: ClassDefContext) -> None:
info = ctx.cls.info
str_type = ctx.api.named_type_or_none('builtins.str', [])
str_type = ctx.api.named_type_or_none("builtins.str", [])
assert str_type is not None
var = Var('__magic__', str_type)
var = Var("__magic__", str_type)
var.info = info
info.names['__magic__'] = SymbolTableNode(MDEF, var)
info.names["__magic__"] = SymbolTableNode(MDEF, var)


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