8000 Implementation of PEP 673 (typing.Self) by Gobot1234 · Pull Request #11666 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Implementation of PEP 673 (typing.Self) #11666

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

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
acf87a3
Much better initial implementation of typing.Self
Gobot1234 Aug 28, 2021
7a6d771
Some extra stuff
Gobot1234 Oct 2, 2021
b1d67ca
Slight improvements
Gobot1234 Nov 5, 2021
c09d95f
Merge branch 'master' into master
Gobot1234 Dec 5, 2021
6a7a084
Remove removed type
Gobot1234 Dec 5, 2021
2ac45c9
Update meet.py
Gobot1234 Dec 5, 2021
1ebe034
Update mypy/type_visitor.py
Gobot1234 Dec 5, 2021
0e6d128
Fix most of the CI issues and respond to comments
Gobot1234 Dec 6, 2021
f844fbe
Merge branch 'master' of https://github.com/Gobot1234/mypy
Gobot1234 Dec 6, 2021
5904918
Merge remote-tracking branch 'upstream/master'
Gobot1234 Jan 14, 2022
e932f52
Merge branch 'master' into master
Gobot1234 Feb 16, 2022
ff779e8
I think this works properly now
Gobot1234 Feb 18, 2022
f94254f
Merge branch 'master' of https://github.com/Gobot1234/mypy
Gobot1234 Feb 18, 2022
c9b2ac9
Merge branch 'master' into master
Gobot1234 Feb 18, 2022
ad0b9b0
Merge remote-tracking branch 'origin/master' into gobot-master
erikkemperman May 20, 2022
6766132
Make tests pass
erikkemperman May 20, 2022
cada36a
Unit tests
erikkemperman May 20, 2022
68c1339
Merge pull request #1 from erikkemperman/gobot-master
Gobot1234 Jun 22, 2022
46d8b70
Merge remote-tracking branch 'upstream/master'
Gobot1234 Jun 22, 2022
fb6d552
I don't think this is entirely correct but lets see
Gobot1234 Jun 22, 2022
6c71758
Fix tests
Gobot1234 Jun 27, 2022
791c9e3
Fixes for signatures of form (type[Self]/Self) -> Self
Gobot1234 Jul 1, 2022
09e966e
Fix some CI
Gobot1234 Jul 1, 2022
ce2d5fa
Fix some CI failures
Gobot1234 Jul 6, 2022
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
Prev Previous commit
Next Next commit
Fix most of the CI issues and respond to comments
  • Loading branch information
Gobot1234 committed Dec 6, 2021
commit 0e6d128bbd00952b4ea3e5434c1ec1a91108c943
6 changes: 4 additions & 2 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@ def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None:
self_type = leading_type.item if isinstance(leading_type, TypeType) else leading_type
fullname = None
# bind any SelfTypes
assert isinstance(func.type, CallableType)
for idx, arg in enumerate(func.type.arg_types):
if self.is_self_type(arg):
if func.is_static:
Expand All @@ -692,7 +693,9 @@ def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None:
if self.is_self_type(func.type.ret_type):
if fullname is None:
self.lookup_qualified(func.type.ret_type.name, func.type.ret_type)
fullname = self.lookup_qualified(func.type.ret_type.name, func.type.ret_type).node.fullname
table_node = self.lookup_qualified(func.type.ret_type.name, func.type.ret_type)
assert isinstance(table_node, SymbolTableNode) and table_node.node
fullname = cast(str, table_node.node.fullname)
if func.is_static:
self.fail(
"Self types in the annotations of staticmethods are not supported, "
Expand Down Expand Up @@ -5159,7 +5162,6 @@ def visit_placeholder_type(self, t: PlaceholderType) -> bool:
def has_placeholder(typ: Type) -> bool:
"""Check if a type contains any placeholder types (recursively)."""
return typ.accept(HasPlaceholders())
return t


def replace_implicit_first_type(sig: FunctionLike, new: Type) -> FunctionLike:
Expand Down
8 changes: 7 additions & 1 deletion mypy/server/astdiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class level -- these are handled at attribute level (say, 'mod.Cls.method'
FuncBase, OverloadedFuncDef, FuncItem, MypyFile, UNBOUND_IMPORTED
)
from mypy.types import (
Type, TypeGuardType, TypeVisitor, UnboundType, AnyType, NoneType, UninhabitedType,
SelfType, Type, TypeGuardType, TypeVisitor, UnboundType, AnyType, NoneType, UninhabitedType,
ErasedType, DeletedType, Instance, TypeVarType, CallableType, TupleType, TypedDictType,
UnionType, Overloaded, PartialType, TypeType, LiteralType, TypeAliasType
)
Expand Down Expand Up @@ -306,6 +306,12 @@ def visit_type_var(self, typ: TypeVarType) -> SnapshotItem:
snapshot_type(typ.upper_bound),
typ.variance)

def visit_self_type(self, typ: SelfType) -> SnapshotItem:
return ('SelfType',
typ.fullname,
snapshot_type(typ.instance)
)

def visit_callable_type(self, typ: CallableType) -> SnapshotItem:
# FIX generics
return ('CallableType',
Expand Down
5 changes: 4 additions & 1 deletion mypy/server/astmerge.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
)
from mypy.traverser import TraverserVisitor
from mypy.types import (
Type, SyntheticTypeVisitor, Instance, AnyType, NoneType, CallableType, ErasedType, DeletedType,
SelfType, Type, SyntheticTypeVisitor, Instance, AnyType, NoneType, CallableType, ErasedType, DeletedType,
TupleType, TypeType, TypeVarType, TypedDictType, UnboundType, UninhabitedType, UnionType,
Overloaded, TypeVarType, TypeList, CallableArgument, EllipsisType, StarType, LiteralType,
RawExpressionType, PartialType, PlaceholderType, TypeAliasType, TypeGuardType
Expand Down Expand Up @@ -410,6 +410,9 @@ def visit_type_var(self, typ: TypeVarType) -> None:
for value in typ.values:
value.accept(self)

def visit_self_type(self, typ: SelfType) -> None:
typ.instance.accept(self)

def visit_typeddict_type(self, typ: TypedDictType) -> None:
for value_type in typ.items.values():
value_type.accept(self)
Expand Down
10 changes: 9 additions & 1 deletion mypy/server/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class 'mod.Cls'. This can also refer to an attribute inherited from a
)
from mypy.traverser import TraverserVisitor
from mypy.types import (
Type, Instance, AnyType, NoneType, TypeVisitor, CallableType, DeletedType, PartialType,
SelfType, Type, Instance, AnyType, NoneType, TypeVisitor, CallableType, DeletedType, PartialType,
TupleType, TypeType, TypeVarType, TypedDictType, UnboundType, UninhabitedType, UnionType,
FunctionLike, Overloaded, TypeOfAny, LiteralType, ErasedType, get_proper_type, ProperType,
TypeAliasType, TypeGuardType
Expand Down Expand Up @@ -957,6 +957,14 @@ def visit_type_var(self, typ: TypeVarType) -> List[str]:
triggers.extend(self.get_type_triggers(val))
return triggers

def visit_self_type(self, typ: SelfType) -> List[str]:
triggers = []
if typ.fullname:
triggers.append(make_trigger(typ.fullname))
if typ.instance:
triggers.extend(self.get_type_triggers(typ.instance))
return triggers

def visit_typeddict_type(self, typ: TypedDictType) -> List[str]:
triggers = []
for item in typ.items.values():
Expand Down
2 changes: 1 addition & 1 deletion mypy/type_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

@trait
@mypyc_attr(allow_interpreted_subclasses=True)
class TypeVisitor(Generic[T], metaclass=ABCMeta):
class TypeVisitor(Generic[T]):
"""Visitor class for types (Type subclasses).

The parameter T is the return type of the visit methods.
Expand Down
2 changes: 1 addition & 1 deletion mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Opt
return self.anal_type(t.args[0])
elif fullname in ('typing_extensions.Self', 'typing.Self'):
try:
bound = self.named_type(self.api.type.fullname)
bound = self.named_type(self.api.type.fullname) # type: ignore
except AttributeError:
return self.fail("Self is unbound", t)
return SelfType(bound, fullname, line=t.line, column=t.column)
Expand Down
2 changes: 2 additions & 0 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,10 @@ def expand(target: Type) -> Type:
if isinstance(arg_type, UnionType):
for idx, item in enumerate(arg_type.items):
if isinstance(item, SelfType):
assert original_type is not None
arg_type.items[idx] = original_type
if isinstance(res.ret_type, SelfType):
assert original_type is not None
res.ret_type = original_type
return cast(F, res)

Expand Down
11 changes: 8 additions & 3 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,11 +428,14 @@ def deserialize(cls, data: JsonDict) -> 'TypeVarType':


class SelfType(ProperType):
name: ClassVar[str] = 'Self'

__slots__ = ('fullname', 'instance')

def __init__(self, instance: 'Instance', fullname: str, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.name = "Self"
self.fullname = fullname
self.instance: 'Instance' = instance
self.instance = instance
self.line = line
self.column = column

Expand All @@ -449,7 +452,9 @@ def serialize(self) -> JsonDict:
@classmethod
def deserialize(cls, data: JsonDict) -> 'SelfType':
assert data['.class'] == 'SelfType'
return cls(deserialize_type(data['instance']), data['fullname'])
instance = deserialize_type(data['instance'])
assert isinstance(instance, Instance)
return cls(instance, data['fullname'])


class ParamSpecType(TypeVarLikeType):
Expand Down
13 changes: 13 additions & 0 deletions runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import sys

from mypy.version import __version__
from mypy.build import build, BuildSource, Options

print(__version__)

options = Options()
options.show_traceback = True
options.raise_exceptions = True
options.verbosity = 10
result = build([BuildSource("test.py", None, )], options, stderr=sys.stderr, stdout=sys.stdout)
print(*result.errors, sep="\n")
38 changes: 38 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from __future__ import annotations

from typing import Self, TypeVar, Protocol

T = TypeVar("T")


class InstanceOf(Protocol[T]):
@property # type: ignore
def __class__(self) -> T: ... # type: ignore


class MyMetaclass(type):
bar: str

def __new__(mcs: type[MyMetaclass], *args, **kwargs) -> MyMetaclass:
cls = super().__new__(mcs, *args, **kwargs)
cls.bar = "Hello"
return cls

def __mul__(
cls,
count: int,
) -> list[InstanceOf[Self]]:
print(cls)
return [cls()] * count

def __call__(cls, *args, **kwargs) -> InstanceOf[Self]:
return super().__call__(*args, **kwargs)


class Foo(metaclass=MyMetaclass):
THIS: int

reveal_type(Foo)
reveal_type(Foo())
foos = Foo * 3
reveal_type(foos)
0