Skip to main content

Golang-style `defer` with no decorators!

Project description

python-defer

Golang-style defer with no decorators!

Defer is an awesome control flow construct. Python implementations have historically relied on cumbersome decorators or other manual coordination. No more!

Use python-defer to schedule code to be run at the end of a function, whether or not anything fails. Think of it like an automagic finally block that you can use inline anywhere.

Check out the blog post to learn how this was built.

Install

$ pip install python-defer

Usage

The default way to use python-defer is true magic. Simply write your code and append an in defer to it.

from defer import defer

def foo():
  print(", world!") in defer
  print("Hello", end="")
  # do something that might fail...
  assert 1 + 1 == 3
$ python foo.py
Hello, World!
Traceback (most recent call last):
  File "foo.py", line 7, in <module>
    assert 1 + 1 == 3
AssertionError

Sugarfree for me!

If you prefer a more explicit approach, you can use the d function, which takes a lambda.

from defer.sugarfree import defer as d

def foo():
  d(print, "1")
  print("2")
  d(lambda: print("3"))
  raise RuntimeError("oh no!")
  print("4")
$ python foo.py
2
3
1
Traceback (most recent call last):
  File "foo.py", line 7, in <module>
RuntimeError: oh no!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_defer-0.2.1.tar.gz (3.7 kB view hashes)

Uploaded Source

Built Distribution

python_defer-0.2.1-py3-none-any.whl (5.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page