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 hashes)
Built Distribution
Close
Hashes for ez_context-1.0.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e5f7b32d98903298fa74962b5967efd4984a04217759055549f5d05d35ed6fd1 |
|
MD5 | e154bc9099eb41e29ffdc0da7036b2e4 |
|
BLAKE2b-256 | fe7a18f171fb4bf3ab3c0f9f3f63b64abf27eebde5d6888733fbbb23483d58e2 |