def formatted_payment_amount(payment_details: dict) -> str: """Get the formatted payment amount from a dictionary. In our dictionary, the payment amount is present as pennies. """ return ( # Option.of() takes something that might be null and makes an # Option out of it: Nothing() if it's null, Some(val) if it's not. Option.of(payment_details.get("payment_amount")) # If we got the payment amount, we know it's an int of pennies. # Let's make it a float of dollars. .map(lambda val: val / 100) # Then let's format it into a string! .map("${:.2f}".format) # Now we've got our happy path, so all we need to do is figure # out what to show if our value was missing. In that case, # let's say we just say $0.00 .unwrap_or("$0.00"))
def authenticate(self, user_id: int, password: str) -> bool: """Authenticate a user with their username and password.""" hasher = sha256() hasher.update(password.encode()) exp_pw = hasher.hexdigest() return ( # First, let's get the user! Since this is an Option, we can # ignore the error case and just start chaining! UsersDB().get(user_id) # If we got the user, we want to check their password. # Let's assume we're using MongoDB with no schema, so we don't # even know for sure the password field is going to be set. # So, we flatmap into another Option-generating function, # in this case, we will try to get the password .and_then(lambda user: Option.of(user.get("password"))) # Now we've got the password, so let's check it to get a bool .map(lambda hashed_pw: hashed_pw == exp_pw) # At this point, our happy path is done! We've gotten a bool # representing whether the password matches. All we need to # do to finish is unwrap. For any of our Nothing cases ( # user was not present, password was not present), we can # just return False. .unwrap_or(False))
def test_option_cannot_be_instantiated(self) -> None: """Option cannot be instantiated""" with pytest.raises(NotImplementedError): Option("a")
def test_err_if(self, predicate: t.Callable, val: t.Any, exp: Option) -> None: """Test constructing based on some predicate.""" assert Option.nothing_if(predicate, val) == exp
def test_of(self, val: t.Any, exp: Option) -> None: """Option.of() returns an Option from an Optional.""" assert Option.of(val) == exp
def test_collect(self, options: t.Iterable[Option], exp: Option) -> None: """Test constructing from an iterable of options.""" assert Option.collect(options) == exp
def get(self, user_id: int) -> Option[t.Dict[str, str]]: """Get a user from the "database".""" return Option.of(self._users.get(user_id))
def serialize_date(key: str, _date: date) -> t.Dict[str, str]: return Option.of(_date).map(date_to_str).map(lambda lw: { key: lw }).unwrap_or(dict())