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.
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.1.tar.gz
(3.2 kB
view hashes)
Built Distribution
Close
Hashes for ez_context-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 64427bd1fcd0360bfaa9b36f6561c94b9907482fc8da6a7f40343d1602b9eff9 |
|
MD5 | dc90c0eaa7b3a1b2145ac729e254819c |
|
BLAKE2b-256 | e9c703f3bb084eda077b9280ce22a27c9df51277224ca2933b0c204e7a000e1f |