An ez generator-based context manager
Project description
EZ Context Managers
Allows you to create generator-based context managers without try/finally. Fully static-typed and thread-safe.
Installing
pip install ez_context
Example:
@context_mgr
def example():
print("entering")
yield
print("exiting")
with example as ex:
print("Hello World!")
entering
Hello World!
exiting
Detailed Example:
@context_mgr
def random_value(a=0, b=100):
rand_num: int = random.randint(a, b)
print(f"entering {rand_num}")
# `yield` runs the body of the `with` statement.
# The yielded value is stored in VAR by `with ... as VAR`
error = yield rand_num
# If the body raises an Exception, it's returned here.
# Otherwise, None is returned
print(f"exiting {rand_num}, {error=}")
if isinstance(error, ValueError):
# Return True to suppress the Exception
return True
with random_value(-5, -1) as n:
assert_type(n, int) # statically typed!
print(n)
# Parentheses are optional if there are no arguments.
with random_value as n1:
# Reusable and re-entrant
with random_value as n2:
raise ValueError("CoolBeans")
Created for a comment on this mCoding video.
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
ez_context-1.0.2.tar.gz
(3.2 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ez_context-1.0.2.tar.gz.
File metadata
- Download URL: ez_context-1.0.2.tar.gz
- Upload date:
- Size: 3.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c6bd97f5d294dc864afbba60c66bc8f41e40ef1e42252ca26ae601a7e0828ffd
|
|
| MD5 |
7802bbf57f2bc976ce5ca30a00defc8e
|
|
| BLAKE2b-256 |
9de81e49389f177e0e5a39a4e78822da14346041fbedd57aa253891eed361dc3
|
File details
Details for the file ez_context-1.0.2-py3-none-any.whl.
File metadata
- Download URL: ez_context-1.0.2-py3-none-any.whl
- Upload date:
- Size: 3.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.12.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e5f7b32d98903298fa74962b5967efd4984a04217759055549f5d05d35ed6fd1
|
|
| MD5 |
e154bc9099eb41e29ffdc0da7036b2e4
|
|
| BLAKE2b-256 |
fe7a18f171fb4bf3ab3c0f9f3f63b64abf27eebde5d6888733fbbb23483d58e2
|