Skip to content

Make type function return Type[T] #1787

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
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,11 @@ def check_call(self, callee: Type, args: List[Node],
self.check_argument_types(arg_types, arg_kinds, callee,
formal_to_actual, context,
messages=arg_messages)

ret_val_is_type_obj = is_equivalent(callee.ret_type, self.named_type('builtins.type'))
Copy link
Member

Choose a reason for hiding this comment

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

That's a pretty expensive call, and this case rarely triggers, so the time is usually wasted. I suggest testing the simpler conditions first and doing this call last.

if callee.is_type_obj() and (len(arg_types) == 1) and ret_val_is_type_obj:
callee.ret_type = TypeType(arg_types[0])
Copy link
Member

Choose a reason for hiding this comment

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

This seems fishy -- I wouldn't mutate callee, who knows if it's been shared elsewhere. I think the common pattern is to make a modified copy -- you can find examples of copy_modified() aplenty.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done! I pushed an updated commit for both your comments.


if callable_node:
# Store the inferred callable type.
self.chk.store_type(callable_node, callee)
Expand Down
60 changes: 59 additions & 1 deletion test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -1818,8 +1818,10 @@ def f(a: Type[User]) -> None: pass
@overload
def f(a: int) -> None: pass

def mock() -> type: return User

f(User)
f(type(User)) # E: No overload variant of "f" matches argument types [builtins.type]
f(mock()) # E: No overload variant of "f" matches argument types [builtins.type]
[builtins fixtures/classmethod.py]
[out]

Expand Down Expand Up @@ -1948,3 +1950,59 @@ def f(a: object) -> str: pass
[builtins fixtures/classmethod.py]
[out]

[case testTypeConstructorReturnsTypeType]
class User:
@classmethod
def test_class_method(cls) -> int: pass
@staticmethod
def test_static_method() -> str: pass
def test_instance_method(self) -> None: pass

u = User()

reveal_type(type(u)) # E: Revealed type is 'Type[__main__.User]'
reveal_type(type(u).test_class_method()) # E: Revealed type is 'builtins.int'
reveal_type(type(u).test_static_method()) # E: Revealed type is 'builtins.str'
type(u).test_instance_method() # E: Too few arguments for "test_instance_method" of "User"
[builtins fixtures/classmethod.py]
[out]

[case testObfuscatedTypeConstructorReturnsTypeType]
from typing import TypeVar
class User: pass

f1 = type

A = TypeVar('A')
def f2(func: A) -> A:
return func

u = User()

reveal_type(f1(u)) # E: Revealed type is 'Type[__main__.User]'
reveal_type(f2(type)(u)) # E: Revealed type is 'Type[__main__.User]'
[builtins fixtures/classmethod.py]
[out]

[case testTypeConstructorLookalikeFails]
class User: pass

def fake1(a: object) -> type:
return User
def fake2(a: int) -> type:
return User

reveal_type(type(User())) # E: Revealed type is 'Type[__main__.User]'
reveal_type(fake1(User())) # E: Revealed type is 'builtins.type'
reveal_type(fake2(3)) # E: Revealed type is 'builtins.type'
[builtins fixtures/classmethod.py]
[out]

[case testOtherTypeConstructorsSucceed]
def foo(self) -> int: return self.attr

User = type('User', (object,), {'foo': foo, 'attr': 3})
reveal_type(User) # E: Revealed type is 'builtins.type'
[builtins fixtures/args.py]
[out]

9 changes: 7 additions & 2 deletions test-data/unit/fixtures/args.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Builtins stub used to support *args, **kwargs.

from typing import TypeVar, Generic, Iterable
from typing import TypeVar, Generic, Iterable, Tuple, Dict, Any, overload

Tco = TypeVar('Tco', covariant=True)
T = TypeVar('T')
Expand All @@ -9,7 +9,12 @@
class object:
def __init__(self) -> None: pass

class type: pass
class type:
@overload
def __init__(self, o: object) -> None: pass
@overload
def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: pass

class tuple(Iterable[Tco], Generic[Tco]): pass
class dict(Generic[T, S]): pass

Expand Down
4 changes: 3 additions & 1 deletion test-data/unit/fixtures/classmethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ def mro(self) -> typing.Any: pass

class function: pass

classmethod = object() # Dummy definition.
# Dummy definitions.
classmethod = object()
staticmethod = object()

class int:
@classmethod
Expand Down