Skip to content

Commit

Permalink
Simple type checking of class decorators
Browse files Browse the repository at this point in the history
This does the bare minimum, it checks that the calls are well-type.
It does not check whether applying the decorator makes sense.

Helps with python#3135
  • Loading branch information
euresti committed Feb 5, 2018
1 parent 477f85a commit a0fa761
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
5 changes: 5 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1254,6 +1254,11 @@ def visit_class_def(self, defn: ClassDef) -> None:
# Otherwise we've already found errors; more errors are not useful
self.check_multiple_inheritance(typ)

for decorator in defn.decorators:
# Currently this only checks that the decorator itself is well typed.
# TODO: Check that applying the decorator to the class would do the right thing.
self.expr_checker.accept(decorator)

def check_protocol_variance(self, defn: ClassDef) -> None:
"""Check that protocol definition is compatible with declared
variances of type variables.
Expand Down
11 changes: 10 additions & 1 deletion test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -4115,7 +4115,7 @@ def f() -> type: return M
class C1(six.with_metaclass(M), object): pass # E: Invalid base class
class C2(C1, six.with_metaclass(M)): pass # E: Invalid base class
class C3(six.with_metaclass(A)): pass # E: Metaclasses not inheriting from 'type' are not supported
@six.add_metaclass(A) # E: Metaclasses not inheriting from 'type' are not supported
@six.add_metaclass(A) # E: Metaclasses not inheriting from 'type' are not supported # E: Argument 1 to "add_metaclass" has incompatible type "Type[A]"; expected "Type[type]"
class D3(A): pass
class C4(six.with_metaclass(M), metaclass=M): pass # E: Multiple metaclass definitions
@six.add_metaclass(M) # E: Multiple metaclass definitions
Expand Down Expand Up @@ -4223,3 +4223,12 @@ class C(Any):
reveal_type(self.bar().__name__) # E: Revealed type is 'builtins.str'
[builtins fixtures/type.pyi]
[out]

[case testClassDecoratorIsTypeChecked]
from typing import Callable
def decorate(x: int) -> Callable[[type], type]: # N: "decorate" defined here
...

@decorate(y=17) # E: Unexpected keyword argument "y" for "decorate"
class A:
pass

0 comments on commit a0fa761

Please sign in to comment.