Skip to content

Commit fd02922

Browse files
authored
new challenge: advanced paramspec (laike9m#55)
1 parent 8fbd8e2 commit fd02922

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
TODO:
3+
4+
Add type annotations to the class `Wrap`, so that it can be called with the
5+
same arguments as the function it wraps.
6+
"""
7+
8+
9+
class Wrap:
10+
def __init__(self, func):
11+
self.func = func
12+
13+
def __call__(self, *args, **kwargs):
14+
return self.func(*args, **kwargs)
15+
16+
17+
## End of your code ##
18+
from typing import assert_type
19+
20+
21+
@Wrap
22+
def add(a: int, b: int) -> int:
23+
return a + b
24+
25+
26+
@Wrap
27+
def replace_wildcard(string: str, replacement: str, *, count: int = -1) -> str:
28+
return string.replace("*", replacement, count)
29+
30+
31+
assert_type(add(1, 2), int)
32+
assert_type(replace_wildcard("Hello *", "World"), str)
33+
assert_type(replace_wildcard("Hello *", "World", count=1), str)
34+
replace_wildcard("Hello *", 1) # expect-type-error
35+
replace_wildcard("Hello *", "World", 1) # expect-type-error
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
TODO:
3+
4+
Add type annotations to the class `Wrap`, so that it can be called with the
5+
same arguments as the function it wraps.
6+
"""
7+
from typing import Callable
8+
9+
# Before 3.12 you have to write:
10+
# T = TypeVar('T')
11+
# P = ParamSpec('P')
12+
# class Wrap(Generic[T, P]):
13+
14+
15+
# For Python >= 3.12
16+
class Wrap[T, **P]:
17+
def __init__(self, func: Callable[P, T]) -> None:
18+
self.func = func
19+
20+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
21+
return self.func(*args, **kwargs)
22+
23+
24+
## End of your code ##
25+
from typing import assert_type
26+
27+
28+
@Wrap
29+
def add(a: int, b: int) -> int:
30+
return a + b
31+
32+
33+
@Wrap
34+
def replace_wildcard(string: str, replacement: str, *, count: int = -1) -> str:
35+
return string.replace("*", replacement, count)
36+
37+
38+
assert_type(add(1, 2), int)
39+
assert_type(replace_wildcard("Hello *", "World"), str)
40+
assert_type(replace_wildcard("Hello *", "World", count=1), str)
41+
replace_wildcard("Hello *", 1) # expect-type-error
42+
replace_wildcard("Hello *", "World", 1) # expect-type-error

0 commit comments

Comments
 (0)