File tree Expand file tree Collapse file tree 5 files changed +60
-2
lines changed Expand file tree Collapse file tree 5 files changed +60
-2
lines changed Original file line number Diff line number Diff line change 2
2
TODO:
3
3
4
4
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) .
6
6
"""
7
7
8
8
Original file line number Diff line number Diff line change 2
2
TODO:
3
3
4
4
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) .
6
6
"""
7
7
from typing import TypeVar
8
8
Original file line number Diff line number Diff line change
1
+ [ TypeVar] ( https://docs.python.org/3/library/typing.html#typing.TypeVar ) accepts a ` bound ` argument
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments