Skip to content
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

Fix accessing unannotated implicit class methods #7739

Merged
merged 3 commits into from
Oct 20, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 6 additions & 1 deletion mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,7 +736,12 @@ def analyze_class_attribute_access(itype: Instance,
mx.not_ready_callback(name, mx.context)
return AnyType(TypeOfAny.from_error)
else:
return function_type(cast(FuncBase, node.node), mx.builtin_type('builtins.function'))
assert isinstance(node.node, FuncBase)
# Note: if we are accessing class method on class object, the cls argument is bound.
# Annotated and/or explicit class methods go through other code paths above, for
# unannotated implicit class method we can just drop first argument.
return function_type(node.node, mx.builtin_type('builtins.function'),
no_self=node.node.is_class)


def add_class_tvars(t: ProperType, itype: Instance, isuper: Optional[Instance],
Expand Down
15 changes: 11 additions & 4 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,14 +383,15 @@ def erase_to_union_or_bound(typ: TypeVarType) -> ProperType:
return get_proper_type(typ.upper_bound)


def function_type(func: FuncBase, fallback: Instance) -> FunctionLike:
def function_type(func: FuncBase, fallback: Instance,
no_self: bool = False) -> FunctionLike:
if func.type:
assert isinstance(func.type, FunctionLike)
return func.type
else:
# Implicit type signature with dynamic types.
if isinstance(func, FuncItem):
return callable_type(func, fallback)
return callable_type(func, fallback, no_self=no_self)
else:
# Broken overloads can have self.type set to None.
# TODO: should we instead always set the type in semantic analyzer?
Expand All @@ -407,7 +408,8 @@ def function_type(func: FuncBase, fallback: Instance) -> FunctionLike:


def callable_type(fdef: FuncItem, fallback: Instance,
ret_type: Optional[Type] = None) -> CallableType:
ret_type: Optional[Type] = None,
no_self: bool = False) -> CallableType:
# TODO: somewhat unfortunate duplication with prepare_method_signature in semanal
if fdef.info and not fdef.is_static and fdef.arg_names:
self_type = fill_typevars(fdef.info) # type: Type
Expand All @@ -417,7 +419,7 @@ def callable_type(fdef: FuncItem, fallback: Instance,
else:
args = [AnyType(TypeOfAny.unannotated)] * len(fdef.arg_names)

return CallableType(
typ = CallableType(
args,
fdef.arg_kinds,
[None if argument_elide_name(n) else n for n in fdef.arg_names],
Expand All @@ -428,6 +430,11 @@ def callable_type(fdef: FuncItem, fallback: Instance,
column=fdef.column,
implicit=True,
)
if no_self and typ.arg_types:
typ = typ.copy_modified(arg_types=typ.arg_types[1:],
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we use bind_self here?

Copy link
Member Author

Choose a reason for hiding this comment

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

At first look it seemed to me bind_self may not work, but now it looks OK to add it in the caller, I will now try to do this. Even if we will discover it doesn't work sometimes, we just need to fix it so it works with unannotated methods.

arg_kinds=typ.arg_kinds[1:],
arg_names=typ.arg_names[1:])
return typ


def try_getting_str_literals(expr: Expression, typ: Type) -> Optional[List[str]]:
Expand Down
36 changes: 36 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -6387,6 +6387,42 @@ class MidBase(Base): pass
[file init_subclass/__init__.py]
[builtins fixtures/object_with_init_subclass.pyi]

[case testInitSubclassUnannotated]
class A:
def __init_subclass__(cls, *args, **kwargs):
super().__init_subclass__(*args, **kwargs)

class B(A):
pass

reveal_type(A.__init_subclass__) # N: Revealed type is 'def (*args: Any, **kwargs: Any) -> Any'
[builtins fixtures/object_with_init_subclass.pyi]

[case testInitSubclassUnannotatedMulti]
from typing import ClassVar, List, Type

class A:
registered_classes: ClassVar[List[Type[A]]] = []
def __init_subclass__(cls, *args, register=True, **kwargs):
if register:
cls.registered_classes.append(cls)
super().__init_subclass__(*args, **kwargs)

class B(A): ...
class C(A, register=False): ...
class D(C): ...
[builtins fixtures/object_with_init_subclass.pyi]

[case testClassMethodUnannotated]
class C:
def __new__(cls): ...
@classmethod
def meth(cls): ...

reveal_type(C.meth) # N: Revealed type is 'def () -> Any'
reveal_type(C.__new__) # N: Revealed type is 'def (cls: Type[__main__.C]) -> Any'
[builtins fixtures/classmethod.pyi]

[case testOverrideGenericSelfClassMethod]
from typing import Generic, TypeVar, Type, List

Expand Down
11 changes: 10 additions & 1 deletion test-data/unit/fixtures/object_with_init_subclass.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Sequence, Iterator, TypeVar, Mapping, Iterable, Optional, Union, overload, Tuple, Generic
from typing import Sequence, Iterator, TypeVar, Mapping, Iterable, Optional, Union, overload, Tuple, Generic, List

class object:
def __init__(self) -> None: ...
Expand Down Expand Up @@ -34,6 +34,15 @@ class tuple(Generic[T]): pass
class function: pass
class ellipsis: pass

# copy-pasted from list.pyi
class list(Sequence[T]):
def __iter__(self) -> Iterator[T]: pass
def __mul__(self, x: int) -> list[T]: pass
def __setitem__(self, x: int, v: T) -> None: pass
def __getitem__(self, x: int) -> T: pass
def __add__(self, x: List[T]) -> T: pass
def __contains__(self, item: object) -> bool: pass

# copy-pasted from dict.pyi
class dict(Mapping[KT, VT]):
@overload
Expand Down