2727from . import Unit , Variant , fieldenum , unreachable
2828from .exceptions import IncompatibleBoundError , UnwrapFailedError
2929
30- __all__ = ["Option" , "BoundResult" , "Message" , "Some" , "Success" , "Failed" ]
30+ __all__ = ["Option" , "BoundResult" , "Message" , "Some" , "Success" , "Failed" , "Result" , "Ok" , "Err" ]
3131
3232_MISSING = object ()
3333type _ExceptionTypes = type [BaseException ] | tuple [type [BaseException ], ... ] | UnionType
@@ -347,15 +347,15 @@ def dump(self) -> tuple[E]: ...
347347 def __bool__ (self ) -> bool :
348348 return isinstance (self , Result .Ok )
349349
350- @overload
351- def unwrap (self ) -> R : ...
352-
353350 @overload
354351 def unwrap (self , default : R ) -> R : ...
355352
356353 @overload
357354 def unwrap [T ](self , default : T ) -> R | T : ...
358355
356+ @overload
357+ def unwrap (self ) -> R : ...
358+
359359 def unwrap (self , default = _MISSING ):
360360 match self :
361361 case Result .Ok (value ):
@@ -387,7 +387,7 @@ def as_option(self) -> Option[R]:
387387 def exit (self , error_code : str | int | None = 1 ) -> NoReturn :
388388 sys .exit (0 if self else error_code )
389389
390- def map [NewReturn ](self , func : Callable [[R ], NewReturn ], bound : _ExceptionTypes , / ) -> Result [NewReturn , E ]:
390+ def map [NewReturn ](self , func : Callable [[R ], NewReturn ], / , bound : _ExceptionTypes ) -> Result [NewReturn , E ]:
391391 match self :
392392 case Result .Ok (ok ):
393393 try :
@@ -398,11 +398,32 @@ def map[NewReturn](self, func: Callable[[R], NewReturn], bound: _ExceptionTypes,
398398 else :
399399 raise
400400
401- case Result .Err (error ) as failed :
402- if TYPE_CHECKING :
403- return Result .Err [NewReturn , E ](error )
401+ case Result .Err () as err :
402+ return err # type: ignore
403+
404+ case other :
405+ unreachable (other )
406+
407+ def flatmap [NewResult : Result ](self , func : Callable [[R ], NewResult ], / , bound : _ExceptionTypes ) -> NewResult :
408+ match self :
409+ case Result .Ok (value ):
410+ try :
411+ result = func (value )
412+ except BaseException as exc :
413+ if isinstance (exc , bound ):
414+ return Result .Err (exc ) # type: ignore
415+ else :
416+ raise
417+
418+ if isinstance (result , Result ):
419+ return result
404420 else :
405- return failed
421+ raise TypeError (
422+ f"Expect Result but received { type (result ).__name__ !r} "
423+ )
424+
425+ case Result .Err () as err :
426+ return err # type: ignore
406427
407428 case other :
408429 unreachable (other )
@@ -663,5 +684,7 @@ def dump(self) -> tuple[()]: ...
663684
664685
665686Some = Option .Some
687+ Ok = Result .Ok
688+ Err = Result .Err
666689Success = BoundResult .Success
667690Failed = BoundResult .Failed
0 commit comments