Skip to content

Commit 8b9bf72

Browse files
authored
Fix variance of Law{1,2,3}, Unwrappable, Contextable, and Trampoline (#2564)
1 parent f3a6f54 commit 8b9bf72

10 files changed

Lines changed: 135 additions & 31 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ See [0Ver](https://0ver.org/).
1414
### Bugfixes
1515

1616
- Fix `{Success, Failure}.swap` returning `Any`
17+
- Fix type parameter variance of `Law{1,2,3}`, `Unwrappable`, `Contextable`,
18+
and `Trampoline`
1719

1820
## 0.30.0
1921

‎returns/_internal/pipeline/pipe.pyi‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
from typing import Generic, TypeVar
22

33
_InstanceType = TypeVar('_InstanceType')
4+
_InstanceType_contra = TypeVar('_InstanceType_contra', contravariant=True)
45
_ReturnType = TypeVar('_ReturnType')
6+
_ReturnType_co = TypeVar('_ReturnType_co', covariant=True)
57

68
_PipelineStepType1 = TypeVar('_PipelineStepType1')
79
_PipelineStepType2 = TypeVar('_PipelineStepType2')
@@ -26,8 +28,8 @@ _PipelineStepType20 = TypeVar('_PipelineStepType20')
2628

2729
class _Pipe(
2830
Generic[
29-
_InstanceType,
30-
_ReturnType,
31+
_InstanceType_contra,
32+
_ReturnType_co,
3133
_PipelineStepType1,
3234
_PipelineStepType2,
3335
_PipelineStepType3,
@@ -76,7 +78,7 @@ class _Pipe(
7678
],
7779
/,
7880
) -> None: ...
79-
def __call__(self, instance: _InstanceType) -> _ReturnType: ...
81+
def __call__(self, instance: _InstanceType_contra) -> _ReturnType_co: ...
8082

8183
def pipe( # noqa: WPS451
8284
function1: _PipelineStepType1,

‎returns/interfaces/specific/reader.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,15 @@
4949
_UpdatedType = TypeVar('_UpdatedType')
5050

5151
_ValueType = TypeVar('_ValueType')
52+
_ValueType_co = TypeVar('_ValueType_co', covariant=True)
5253
_EnvType = TypeVar('_EnvType')
54+
_EnvType_contra = TypeVar('_EnvType_contra', contravariant=True)
5355

5456
_ReaderLike2Type = TypeVar('_ReaderLike2Type', bound='ReaderLike2')
5557
_ReaderLike3Type = TypeVar('_ReaderLike3Type', bound='ReaderLike3')
5658

5759

58-
class Contextable(Generic[_ValueType, _EnvType]):
60+
class Contextable(Generic[_ValueType_co, _EnvType_contra]):
5961
"""
6062
Special type we use as a base one for all callble ``Reader`` instances.
6163
@@ -75,7 +77,7 @@ class Contextable(Generic[_ValueType, _EnvType]):
7577
__slots__ = ()
7678

7779
@abstractmethod
78-
def __call__(self, deps: _EnvType) -> _ValueType:
80+
def __call__(self, deps: _EnvType_contra) -> _ValueType_co:
7981
"""Receives one parameter, returns a value. As simple as that."""
8082

8183

@@ -128,7 +130,7 @@ def from_context(
128130

129131
class CallableReader2(
130132
ReaderLike2[_FirstType, _SecondType],
131-
Contextable[_ValueType, _EnvType],
133+
Contextable[_ValueType_co, _EnvType_contra],
132134
):
133135
"""
134136
Intermediate interface for ``ReaderLike2`` + ``__call__`` method.
@@ -193,7 +195,7 @@ def from_context(
193195

194196
class CallableReader3(
195197
ReaderLike3[_FirstType, _SecondType, _ThirdType],
196-
Contextable[_ValueType, _EnvType],
198+
Contextable[_ValueType_co, _EnvType_contra],
197199
):
198200
"""
199201
Intermediate interface for ``ReaderLike3`` + ``__call__`` method.

‎returns/interfaces/unwrappable.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
from abc import abstractmethod
22
from typing import Generic, TypeVar
33

4-
_FirstType = TypeVar('_FirstType')
5-
_SecondType = TypeVar('_SecondType')
4+
_FirstType_co = TypeVar('_FirstType_co', covariant=True)
5+
_SecondType_co = TypeVar('_SecondType_co', covariant=True)
66

77
_UnwrappableType = TypeVar('_UnwrappableType', bound='Unwrappable')
88

99

10-
class Unwrappable(Generic[_FirstType, _SecondType]):
10+
class Unwrappable(Generic[_FirstType_co, _SecondType_co]):
1111
"""
1212
Represents containers that can unwrap and return its wrapped value.
1313
@@ -21,7 +21,7 @@ class Unwrappable(Generic[_FirstType, _SecondType]):
2121
__slots__ = ()
2222

2323
@abstractmethod
24-
def unwrap(self: _UnwrappableType) -> _FirstType:
24+
def unwrap(self: _UnwrappableType) -> _FirstType_co:
2525
"""
2626
Custom magic method to unwrap inner value from container.
2727
@@ -37,7 +37,7 @@ def unwrap(self: _UnwrappableType) -> _FirstType:
3737
"""
3838

3939
@abstractmethod
40-
def failure(self: _UnwrappableType) -> _SecondType:
40+
def failure(self: _UnwrappableType) -> _SecondType_co:
4141
"""
4242
Custom magic method to unwrap inner value from the failed container.
4343

‎returns/primitives/laws.py‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44
from returns.primitives.types import Immutable
55

66
_Caps = TypeVar('_Caps')
7-
_ReturnType = TypeVar('_ReturnType')
8-
_TypeArgType1 = TypeVar('_TypeArgType1')
9-
_TypeArgType2 = TypeVar('_TypeArgType2')
10-
_TypeArgType3 = TypeVar('_TypeArgType3')
7+
_ReturnType_co = TypeVar('_ReturnType_co', covariant=True)
8+
_TypeArgType1_contra = TypeVar('_TypeArgType1_contra', contravariant=True)
9+
_TypeArgType2_contra = TypeVar('_TypeArgType2_contra', contravariant=True)
10+
_TypeArgType3_contra = TypeVar('_TypeArgType3_contra', contravariant=True)
1111

1212
law_definition = staticmethod
1313
"""Special alias to define laws as functions even inside a class."""
@@ -42,17 +42,17 @@ def name(self) -> str:
4242
@final
4343
class Law1(
4444
Law,
45-
Generic[_TypeArgType1, _ReturnType],
45+
Generic[_TypeArgType1_contra, _ReturnType_co],
4646
):
4747
"""Law definition for functions with a single argument."""
4848

4949
__slots__ = ()
5050

51-
definition: Callable[['Law1', _TypeArgType1], _ReturnType]
51+
definition: Callable[['Law1', _TypeArgType1_contra], _ReturnType_co]
5252

5353
def __init__(
5454
self,
55-
function: Callable[[_TypeArgType1], _ReturnType],
55+
function: Callable[[_TypeArgType1_contra], _ReturnType_co],
5656
) -> None:
5757
"""Saves function of one argument to the inner state."""
5858
super().__init__(function)
@@ -61,17 +61,23 @@ def __init__(
6161
@final
6262
class Law2(
6363
Law,
64-
Generic[_TypeArgType1, _TypeArgType2, _ReturnType],
64+
Generic[_TypeArgType1_contra, _TypeArgType2_contra, _ReturnType_co],
6565
):
6666
"""Law definition for functions with two arguments."""
6767

6868
__slots__ = ()
6969

70-
definition: Callable[['Law2', _TypeArgType1, _TypeArgType2], _ReturnType]
70+
definition: Callable[
71+
['Law2', _TypeArgType1_contra, _TypeArgType2_contra],
72+
_ReturnType_co,
73+
]
7174

7275
def __init__(
7376
self,
74-
function: Callable[[_TypeArgType1, _TypeArgType2], _ReturnType],
77+
function: Callable[
78+
[_TypeArgType1_contra, _TypeArgType2_contra],
79+
_ReturnType_co,
80+
],
7581
) -> None:
7682
"""Saves function of two arguments to the inner state."""
7783
super().__init__(function)
@@ -80,22 +86,32 @@ def __init__(
8086
@final
8187
class Law3(
8288
Law,
83-
Generic[_TypeArgType1, _TypeArgType2, _TypeArgType3, _ReturnType],
89+
Generic[
90+
_TypeArgType1_contra,
91+
_TypeArgType2_contra,
92+
_TypeArgType3_contra,
93+
_ReturnType_co,
94+
],
8495
):
8596
"""Law definition for functions with three argument."""
8697

8798
__slots__ = ()
8899

89100
definition: Callable[
90-
['Law3', _TypeArgType1, _TypeArgType2, _TypeArgType3],
91-
_ReturnType,
101+
[
102+
'Law3',
103+
_TypeArgType1_contra,
104+
_TypeArgType2_contra,
105+
_TypeArgType3_contra,
106+
],
107+
_ReturnType_co,
92108
]
93109

94110
def __init__(
95111
self,
96112
function: Callable[
97-
[_TypeArgType1, _TypeArgType2, _TypeArgType3],
98-
_ReturnType,
113+
[_TypeArgType1_contra, _TypeArgType2_contra, _TypeArgType3_contra],
114+
_ReturnType_co,
99115
],
100116
) -> None:
101117
"""Saves function of three arguments to the inner state."""

‎returns/trampolines.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
from typing_extensions import ParamSpec
66

77
_ReturnType = TypeVar('_ReturnType')
8+
_ReturnType_co = TypeVar('_ReturnType_co', covariant=True)
89
_FuncParams = ParamSpec('_FuncParams')
910

1011

1112
@final
12-
class Trampoline(Generic[_ReturnType]):
13+
class Trampoline(Generic[_ReturnType_co]):
1314
"""
1415
Represents a wrapped function call.
1516
@@ -18,13 +19,13 @@ class Trampoline(Generic[_ReturnType]):
1819

1920
__slots__ = ('args', 'func', 'kwargs')
2021

21-
func: Callable[..., _ReturnType]
22+
func: Callable[..., _ReturnType_co]
2223
args: tuple[Any, ...]
2324
kwargs: dict[str, Any]
2425

2526
def __init__( # noqa: WPS451
2627
self,
27-
func: Callable[_FuncParams, _ReturnType],
28+
func: Callable[_FuncParams, _ReturnType_co],
2829
/, # We use pos-only here to be able to store `kwargs` correctly.
2930
*args: _FuncParams.args,
3031
**kwargs: _FuncParams.kwargs,
@@ -34,7 +35,7 @@ def __init__( # noqa: WPS451
3435
self.args = args
3536
self.kwargs = kwargs
3637

37-
def __call__(self) -> _ReturnType:
38+
def __call__(self) -> _ReturnType_co:
3839
"""Call wrapped function with given arguments."""
3940
return self.func(*self.args, **self.kwargs)
4041

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
- case: contextable_correct_cast
2+
disable_cache: false
3+
main: |
4+
from returns.interfaces.specific.reader import Contextable
5+
6+
first: Contextable[bool, object]
7+
second: Contextable[int, str] = first
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
- case: unwrappable_correct_cast
2+
disable_cache: false
3+
main: |
4+
from returns.interfaces.unwrappable import Unwrappable
5+
6+
first: Unwrappable[bool, ValueError]
7+
second: Unwrappable[int, Exception] = first
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
- case: law1_correct_cast
2+
disable_cache: false
3+
main: |
4+
from returns.primitives.laws import Law1
5+
6+
first: Law1[int, bool]
7+
second: Law1[bool, int] = first
8+
9+
10+
- case: law1_wrong_cast
11+
disable_cache: false
12+
main: |
13+
from returns.primitives.laws import Law1
14+
15+
first: Law1[bool, int]
16+
second: Law1[int, bool] = first
17+
out: |
18+
main:4: error: Incompatible types in assignment (expression has type "Law1[bool, int]", variable has type "Law1[int, bool]") [assignment]
19+
20+
21+
- case: law2_correct_cast
22+
disable_cache: false
23+
main: |
24+
from returns.primitives.laws import Law2
25+
26+
first: Law2[int, int, bool]
27+
second: Law2[bool, bool, int] = first
28+
29+
30+
- case: law2_wrong_cast
31+
disable_cache: false
32+
main: |
33+
from returns.primitives.laws import Law2
34+
35+
first: Law2[bool, bool, int]
36+
second: Law2[int, int, bool] = first
37+
out: |
38+
main:4: error: Incompatible types in assignment (expression has type "Law2[bool, bool, int]", variable has type "Law2[int, int, bool]") [assignment]
39+
40+
41+
- case: law3_correct_cast
42+
disable_cache: false
43+
main: |
44+
from returns.primitives.laws import Law3
45+
46+
first: Law3[int, int, int, bool]
47+
second: Law3[bool, bool, bool, int] = first
48+
49+
50+
- case: law3_wrong_cast
51+
disable_cache: false
52+
main: |
53+
from returns.primitives.laws import Law3
54+
55+
first: Law3[bool, bool, bool, int]
56+
second: Law3[int, int, int, bool] = first
57+
out: |
58+
main:4: error: Incompatible types in assignment (expression has type "Law3[bool, bool, bool, int]", variable has type "Law3[int, int, int, bool]") [assignment]

‎typesafety/test_trampolines/test_trampoline.yml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,12 @@
5656
reveal_type(t.func) # N: Revealed type is "def (*Any, **Any) -> int"
5757
reveal_type(t.args) # N: Revealed type is "tuple[Any, ...]"
5858
reveal_type(t.kwargs) # N: Revealed type is "dict[str, Any]"
59+
60+
61+
- case: trampoline_correct_cast
62+
disable_cache: false
63+
main: |
64+
from returns.trampolines import Trampoline
65+
66+
first: Trampoline[bool]
67+
second: Trampoline[int] = first

0 commit comments

Comments
 (0)