Coverage for sources/mimeogram/__/generics.py: 100%
30 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-05 19:15 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-05 19:15 +0000
1# vim: set filetype=python fileencoding=utf-8:
2# -*- coding: utf-8 -*-
4#============================================================================#
5# #
6# Licensed under the Apache License, Version 2.0 (the "License"); #
7# you may not use this file except in compliance with the License. #
8# You may obtain a copy of the License at #
9# #
10# http://www.apache.org/licenses/LICENSE-2.0 #
11# #
12# Unless required by applicable law or agreed to in writing, software #
13# distributed under the License is distributed on an "AS IS" BASIS, #
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
15# See the License for the specific language governing permissions and #
16# limitations under the License. #
17# #
18#============================================================================#
21''' Generic types. '''
22# TODO: Independent package.
25from . import imports as __
28T = __.typx.TypeVar( 'T' ) # generic
29U = __.typx.TypeVar( 'U' ) # generic
30E = __.typx.TypeVar( 'E', bound = Exception ) # error
33class Result( __.immut.Object, __.typx.Generic[ T, E ] ):
34 ''' Either a value or an error. '''
35 # TODO: Protocol class.
37 def is_error( self ) -> bool:
38 ''' Returns ``True`` if error result. Else ``False``. '''
39 return isinstance( self, Error )
41 def is_value( self ) -> bool:
42 ''' Returns ``True`` if value result. Else ``False``. '''
43 return isinstance( self, Value )
45 @__.abc.abstractmethod
46 def extract( self ) -> T:
47 ''' Extracts value from result. Else, raises error from result.
49 Similar to Result.unwrap in Rust.
50 '''
51 raise NotImplementedError
53 @__.abc.abstractmethod
54 def transform(
55 self, function: __.typx.Callable[ [ T ], U ]
56 ) -> __.typx.Self | "Result[ U, E ]":
57 ''' Transforms value in value result. Ignores error result.
59 Similar to Result.map in Rust.
60 '''
61 raise NotImplementedError
64class Value( Result[ T, E ] ):
65 ''' Result of successful computation. '''
67 __match_args__ = ( 'value', )
68 __slots__ = ( 'value', )
70 value: T
72 def __init__( self, value: T ): self.value = value
74 def extract( self ) -> T: return self.value
76 def transform(
77 self, function: __.typx.Callable[ [ T ], U ]
78 ) -> "Result[ U, E ]": return Value( function( self.value ) )
81class Error( Result[ T, E ] ):
82 ''' Result of failed computation. '''
84 __match_args__ = ( 'error', )
85 __slots__ = ( 'error', )
87 error: E
89 def __init__( self, error: E ): self.error = error
91 def extract( self ) -> __.typx.Never: raise self.error
93 def transform(
94 self, function: __.typx.Callable[ [ T ], U ]
95 ) -> __.typx.Self: return self
98GenericResult: __.typx.TypeAlias = Result[ __.typx.Any, Exception ]