• Kirill Smelkov's avatar
    Add support for defer & recover · 5146eb0b
    Kirill Smelkov authored
    `defer` allows to schedule a cleanup to be executed when current function
    returns. It is similar to `try`/`finally` but does not force the cleanup part
    to be far away in the end. For example::
    
       wc = wcfs.join(zurl)    │     wc = wcfs.join(zurl)
       defer(wc.close)         │     try:
                               │        ...
       ...                     │        ...
       ...                     │        ...
       ...                     │     finally:
                               │        wc.close()
    
    For completeness there is `recover` and `panic` that allow to program with
    Go-style error handling, for example::
    
       def _():
          r = recover()
          if r is not None:
             print("recovered. error was: %s" % (r,))
       defer(_)
    
       ...
    
       panic("aaa")
    
    But `recover` and `panic` are probably of less utility since they can be
    practically natively modelled with `try`/`except`.
    
    If `defer` is used, the function that uses it must be wrapped with `@func` or
    `@method` decorators.
    
    The implementation is partly inspired by work of Denis Kolodin:
    
    - https://habr.com/post/191786
    - https://stackoverflow.com/a/43028386/9456786
    5146eb0b
README.rst 3.05 KB