Skip to content

Commit 2651fcb

Browse files
committed
Add basics of delegate decorator: see python/typing#270
1 parent acfcfc6 commit 2651fcb

5 files changed

Lines changed: 122 additions & 2 deletions

File tree

‎extensions/mypy_extensions.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,10 @@ def __getitem__(self, args):
157157

158158

159159
FlexibleAlias = _FlexibleAliasCls()
160+
161+
162+
def delegate(base_func, exclude=()):
163+
def decorator(func):
164+
return func
165+
166+
return decorator

‎mypy/checker.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
SymbolTable, Statement, MypyFile, Var, Expression, Lvalue, Node,
1414
OverloadedFuncDef, FuncDef, FuncItem, FuncBase, TypeInfo,
1515
ClassDef, Block, AssignmentStmt, NameExpr, MemberExpr, IndexExpr,
16-
TupleExpr, ListExpr, ExpressionStmt, ReturnStmt, IfStmt,
16+
TupleExpr, ListExpr, SetExpr, ExpressionStmt, ReturnStmt, IfStmt,
1717
WhileStmt, OperatorAssignmentStmt, WithStmt, AssertStmt,
1818
RaiseStmt, TryStmt, ForStmt, DelStmt, CallExpr, IntExpr, StrExpr,
1919
UnicodeExpr, OpExpr, UnaryExpr, LambdaExpr, TempNode, SymbolTableNode,
@@ -2733,6 +2733,27 @@ def visit_decorator(self, e: Decorator) -> None:
27332733
self.fail('Single overload definition, multiple required', e)
27342734
continue
27352735
dec = self.expr_checker.accept(d)
2736+
2737+
if (isinstance(d, CallExpr)
2738+
and getattr(d.callee, 'fullname', '') == 'mypy_extensions.delegate'
2739+
and d.args
2740+
and isinstance(sig, CallableType) # TODO allow Overloaded?
2741+
and sig.is_kw_arg):
2742+
# TODO how should this combine with other decorators?
2743+
delegate_sig = self.expr_checker.accept(d.args[0])
2744+
if not isinstance(delegate_sig, CallableType):
2745+
continue # TODO error message?
2746+
exclude = []
2747+
if d.arg_names[1:2] == ['exclude']:
2748+
exclude = d.args[1]
2749+
if not (isinstance(exclude, (ListExpr, TupleExpr, SetExpr))
2750+
and all(isinstance(ex, StrExpr)
2751+
for ex in exclude.items)):
2752+
continue # TODO error message?
2753+
exclude = [s.value for s in cast(List[StrExpr], exclude.items)]
2754+
sig = self._delegated_sig(delegate_sig, sig, exclude)
2755+
continue
2756+
27362757
temp = self.temp_node(sig)
27372758
fullname = None
27382759
if isinstance(d, RefExpr):
@@ -2751,6 +2772,27 @@ def visit_decorator(self, e: Decorator) -> None:
27512772
if e.func.info and not e.func.is_dynamic():
27522773
self.check_method_override(e)
27532774

2775+
def _delegated_sig(self, delegate_sig, sig, exclude):
2776+
# TODO: also delegate *args (currently only does **kwargs)
2777+
exclude += sig.arg_names
2778+
args = [(name,
2779+
kind if kind != nodes.ARG_OPT else nodes.ARG_NAMED_OPT,
2780+
typ)
2781+
for (name, kind, typ) in
2782+
zip(delegate_sig.arg_names,
2783+
delegate_sig.arg_kinds,
2784+
delegate_sig.arg_types)
2785+
if kind not in (nodes.ARG_POS, nodes.ARG_STAR)
2786+
and name not in exclude]
2787+
names, kinds, types = map(list, zip(*args))
2788+
# **kwargs are always last in the signature, so we remove them with [:-1]
2789+
sig = sig.copy_modified(
2790+
arg_names=sig.arg_names[:-1] + names,
2791+
arg_kinds=sig.arg_kinds[:-1] + kinds,
2792+
arg_types=sig.arg_types[:-1] + types,
2793+
)
2794+
return sig
2795+
27542796
def check_for_untyped_decorator(self,
27552797
func: FuncDef,
27562798
dec_type: Type,

‎mypy/test/testcheck.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
'check-lists.test',
4444
'check-namedtuple.test',
4545
'check-typeddict.test',
46+
'check-delegate.test',
4647
'check-type-aliases.test',
4748
'check-ignore.test',
4849
'check-type-promotion.test',

‎test-data/unit/check-delegate.test‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
-- Delegating arguments
2+
3+
[case testSimpleDelegation]
4+
from mypy_extensions import delegate
5+
6+
def raw(name: str = 'he', age: int = 42):
7+
return '%s is %s' % (name, age)
8+
9+
@delegate(raw)
10+
def cooked(**kwargs):
11+
return raw(**kwargs)
12+
13+
reveal_type(cooked) # E: Revealed type is 'def (*, name: builtins.str =, age: builtins.int =) -> Any'
14+
cooked(x=56) # E: Unexpected keyword argument "x" for "cooked"
15+
[builtins fixtures/dict.pyi]
16+
17+
18+
[case testDelegationWithPositionalArg]
19+
from mypy_extensions import delegate
20+
21+
def raw(foo, name='he', age=42):
22+
return '%s is %s' % (name, age)
23+
24+
@delegate(raw)
25+
def cooked(foo, bar, **kwargs):
26+
return raw(foo, **kwargs)
27+
28+
reveal_type(cooked) # E: Revealed type is 'def (foo: Any, bar: Any, *, name: Any =, age: Any =) -> Any'
29+
cooked(3) # E: Too few arguments for "cooked"
30+
cooked(3, 4)
31+
cooked(3, 4, 5) # E: Too many positional arguments for "cooked"
32+
cooked(3, 4, name='bob')
33+
cooked(3, 4, x='bob') # E: Unexpected keyword argument "x" for "cooked"
34+
[builtins fixtures/dict.pyi]
35+
36+
37+
[case testDelegationWithKeywordOnlyArg]
38+
from mypy_extensions import delegate
39+
40+
def raw(*, name, age):
41+
return '%s is %s' % (name, age)
42+
43+
@delegate(raw)
44+
def cooked(foo, bar, **kwargs):
45+
return raw(foo, **kwargs)
46+
47+
reveal_type(cooked) # E: Revealed type is 'def (foo: Any, bar: Any, *, name: Any, age: Any) -> Any'
48+
cooked(3, 4, name='bob', age=34)
49+
cooked(3, 4, name='bob') # E: Missing named argument "age" for "cooked"
50+
cooked(3, 4, x='bob') # E: Unexpected keyword argument "x" for "cooked"
51+
[builtins fixtures/dict.pyi]
52+
53+
54+
[case testDelegationWithExclude]
55+
from mypy_extensions import delegate
56+
57+
def raw(name='he', age=42):
58+
return '%s is %s' % (name, age)
59+
60+
@delegate(raw, exclude=['name'])
61+
def cooked(**kwargs):
62+
return raw(name='bob', **kwargs)
63+
64+
reveal_type(cooked) # E: Revealed type is 'def (*, age: Any =) -> Any'
65+
cooked(age=32)
66+
cooked(name='me') # E: Unexpected keyword argument "name" for "cooked"
67+
[builtins fixtures/dict.pyi]

‎test-data/unit/lib-stub/mypy_extensions.pyi‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# NOTE: Requires fixtures/dict.pyi
2-
from typing import Dict, Type, TypeVar, Optional, Any, Generic
2+
from typing import Dict, Type, TypeVar, Optional, Any, Generic, Callable, List
33

44
_T = TypeVar('_T')
55
_U = TypeVar('_U')
@@ -27,3 +27,6 @@ def trait(cls: Any) -> Any: ...
2727
class NoReturn: pass
2828

2929
class FlexibleAlias(Generic[_T, _U]): ...
30+
31+
32+
def delegate(base_func: Callable, exclude: List[str] = ()) -> Callable: ...

0 commit comments

Comments
 (0)