项目作者: L3viathan

项目描述 :
Go-style errors in Python, with a twist
高级语言: Python
项目地址: git://github.com/L3viathan/gofuncyourself.git
创建时间: 2020-04-24T15:06:15Z
项目社区:https://github.com/L3viathan/gofuncyourself

开源协议:

下载


gofuncyourself

Golang has this… interesting approach to exception handling where functions return a tuple of the actual result and a error (that may be nil).

This is a reimagining of the same concept applied to Python. It comes in form of a decorator:

  1. from gofuncyourself import gofunc
  2. @gofunc
  3. def div(x, y):
  4. return x / y

If you now call div(16, 2) it will return (8, None), where None
references the fact that no error has occurred.

If you instead do something like res, err = div(7, 0) then res will be
None, and err will not; instead it will be a special error object that
contains the exception that was caught in err.exception.

Functions decorated with gofunc are to be called like this:

  1. res, err = div(x, y)
  2. if err:
  3. ... # handle exception

But wait, there’s more!


What if you forget to check for an error? gofuncyourself protects you from
that, by raising the exception one second later, if you didn’t do if err:.
The delay can be adjusted by passing a delay keyword argument to the decorator. For example, if you want to make sure the error is handled swiftly:

  1. @gofunc(delay=0.1) # only wait for 100ms before raising
  2. def div(x, y):
  3. return x / y

Installation

  1. pip install gofuncyourself

Acknowledgements