Skip to content

Now __new__ in a metaclass must return a subtype of type #11420

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 1 commit into from
Nov 1, 2021
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
12 changes: 11 additions & 1 deletion mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1104,7 +1104,17 @@ def check___new___signature(self, fdef: FuncDef, typ: CallableType) -> None:
bound_type = bind_self(typ, self_type, is_classmethod=True)
# Check that __new__ (after binding cls) returns an instance
# type (or any).
if not isinstance(get_proper_type(bound_type.ret_type),
if isinstance(fdef.info, TypeInfo) and fdef.info.is_metaclass():
# This is a metaclass, so it must return a new unrelated type.
self.check_subtype(
bound_type.ret_type,
self.type_type(),
fdef,
message_registry.INVALID_NEW_TYPE,
'returns',
'but must return a subtype of'
)
elif not isinstance(get_proper_type(bound_type.ret_type),
(AnyType, Instance, TupleType)):
self.fail(
message_registry.NON_INSTANCE_NEW_TYPE.format(
Expand Down
31 changes: 31 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -6419,6 +6419,37 @@ class B(A):

reveal_type(B()) # N: Revealed type is "__main__.B"

[case testNewReturnType10]
# https://github.com/python/mypy/issues/11398
from typing import Type

class MyMetaClass(type):
def __new__(cls, name, bases, attrs) -> Type['MyClass']:
pass

class MyClass(metaclass=MyMetaClass):
pass

[case testNewReturnType11]
# https://github.com/python/mypy/issues/11398
class MyMetaClass(type):
def __new__(cls, name, bases, attrs) -> type:
pass

class MyClass(metaclass=MyMetaClass):
pass

[case testNewReturnType12]
# https://github.com/python/mypy/issues/11398
from typing import Type

class MyMetaClass(type):
def __new__(cls, name, bases, attrs) -> int: # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "type")
pass

class MyClass(metaclass=MyMetaClass):
pass

[case testGenericOverride]
from typing import Generic, TypeVar, Any

Expand Down