Skip to content

Commit f64bb3e

Browse files
committed
Add generic3 that exercises bound
1 parent b0b7627 commit f64bb3e

File tree

5 files changed

+60
-2
lines changed

5 files changed

+60
-2
lines changed

challenges/intermediate-generic2/question.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
TODO:
33
44
The function `add` accepts two arguments and returns a value, they all have the same type.
5-
The type can only be str or int.
5+
The type can only be str or int (or their subclasses).
66
"""
77

88

challenges/intermediate-generic2/solution.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
TODO:
33
44
The function `add` accepts two arguments and returns a value, they all have the same type.
5-
The type can only be str or int.
5+
The type can only be str or int (or their subclasses).
66
"""
77
from typing import TypeVar
88

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[TypeVar](https://docs.python.org/3/library/typing.html#typing.TypeVar) accepts a `bound` argument
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
TODO:
3+
4+
The function `add` accepts one argument and returns a value, they all have the same type.
5+
The type can only be int or subclasses of int.
6+
"""
7+
8+
9+
def add(a):
10+
return a
11+
12+
13+
## End of your code ##
14+
from typing import assert_type
15+
16+
17+
class MyInt(int):
18+
pass
19+
20+
21+
assert_type(add(1), int)
22+
assert_type(add(MyInt(1)), MyInt)
23+
assert_type(add("1"), str) # expect-type-error
24+
add(["1"], ["2"]) # expect-type-error
25+
add("1", 2) # expect-type-error
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
TODO:
3+
4+
The function `add` accepts one argument and returns a value, they all have the same type.
5+
The type can only be int or subclasses of int.
6+
"""
7+
from typing import TypeVar
8+
9+
T = TypeVar("T", bound=int)
10+
11+
12+
def add(a: T) -> T:
13+
return a
14+
15+
16+
# For Python >= 3.12
17+
# def add[T: int](a: T) -> T:
18+
# return a
19+
20+
## End of your code ##
21+
from typing import assert_type
22+
23+
24+
class MyInt(int):
25+
pass
26+
27+
28+
assert_type(add(1), int)
29+
assert_type(add(MyInt(1)), MyInt)
30+
assert_type(add("1"), str) # expect-type-error
31+
add(["1"], ["2"]) # expect-type-error
32+
add("1", 2) # expect-type-error

0 commit comments

Comments
 (0)