Skip to content

lsfischer/monads

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Monads

Basic monad helper classes to help you write more strongly typed python

Example usage

from monads import Result
from enum import Enum
from dataclasses import dataclass

@dataclass
class User:
    user_id: str
    name: str
    
    
class UserFailureReason(Enum):
    USER_NOT_FOUND = "user_not_found"
    SOME_OTHER_REASON = "some_other_reason"
    

def get_user(user_id: str) -> Result[User, UserFailureReason]:
    """ Retrieve the user from the DB given its ID """
    db_result = {"user_id": "1", "name": "John Doe"}
    
    if not db_result:
        return Result.error(UserFailureReason.USER_NOT_FOUND)
    
    user = User(db_result["user_id"], db_result["name"])
    return Result.ok(user)


get_user(user_id="1").map(lambda x: x.name).or_else_throw()
# Output: John Doe

However if the user was not present in our DB then

get_user(user_id="1").map(lambda x: x.name).or_else_throw()
# Output: NotImplementedError: No success value present, but contains an error instead: UserFailureReason.USER_NOT_FOUND

About

Monad utility classes in python

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages