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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file python_defer-0.2.1.tar.gz
.
File metadata
- Download URL: python_defer-0.2.1.tar.gz
- Upload date:
- Size: 3.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.5.1 CPython/3.11.0 Darwin/22.1.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6322328194054f6eb21372dcf0f7ac0b43c5e65218735aacc779fa4fbee27024 |
|
MD5 | b352b4301160c359f4def540a2d981a7 |
|
BLAKE2b-256 | 9a110f00a8d598eccef9ef0435cf1deafc4592a552ba4dc73ea8a72a00ab8b79 |
File details
Details for the file python_defer-0.2.1-py3-none-any.whl
.
File metadata
- Download URL: python_defer-0.2.1-py3-none-any.whl
- Upload date:
- Size: 5.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.5.1 CPython/3.11.0 Darwin/22.1.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | df3736272a5c5349ce577f2d366508e4cd7e1eb0cbaf52a472ee1e1778d53ff9 |
|
MD5 | 70d7436b7561bae58dc296f9d7bf16b4 |
|
BLAKE2b-256 | 2b53a6a9ff260449aa8c7d7eedc07965ec833471835bff0455e8076a27e40bc1 |