{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/go-rusty-with-exception-handling/",
  "description": "Implement Rust-style Result types for type-safe exception handling in Python using generic Ok and Err types inspired by Black formatter.",
  "path": "/python/go-rusty-with-exception-handling/",
  "publishedAt": "2022-02-02T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "Error Handling",
    "Typing"
  ],
  "textContent": "While grokking Black formatter's codebase, I came across this [Rust-influenced error\nhandling model] that offers an interesting way of handling exceptions in Python. Exception\nhandling in Python usually follows the EAFP paradigm where it's easier to ask for\nforgiveness than permission.\n\nHowever, Rust has this [recoverable error] handling workflow that leverages generic Enums. I\nwanted to explore how Black emulates that in Python. This is how it works:\n\nIn the above snippet, two generic types Ok and Err represent the return type and the\nerror types of a callable respectively. These two generics were then combined into one\nResult generic type. You'd use the Result generic to handle exceptions as follows:\n\nThis will print:\n\nIf you run Mypy on the snippet, it'll succeed as well.\n\nYou can also apply constraints on the return or exception types as follows:\n\nRunning the script will give you this:\n\nIn this case, Mypy will catch the type inconsistency before runtime.\n\nBreadcrumbs\n\nBlack extensively uses this [rusty pattern] in the transformation part of the codebase. This\nshowed me another way of thinking about handling recoverable exceptions while ensuring type\nsafety in a Python codebase.\n\nHowever, I wouldn't go about and mindlessly refactor any exception handling logic that I\ncome across to follow this pattern. You might find it useful if you need to handle\nexceptions in a recoverable fashion and need additional type safety around the logic.\n\nFurther reading\n\n- [Beginner's guide to error handling in Rust]\n\n\n\n\n[rust-influenced error handling model]:\n    https://github.com/psf/black/blob/main/src/black/rusty.py\n\n[recoverable error]:\n    https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html\n\n[rusty pattern]:\n    https://github.com/psf/black/blob/6417c99bfdbdc057e4a10aeff9967a751f4f85e9/src/black/trans.py#L61\n\n[beginner's guide to error handling in rust]:\n    https://www.sheshbabu.com/posts/rust-error-handling/",
  "title": "Go Rusty with exception handling in Python"
}