Skip to content

Commit

Permalink
Clearer error message if async context manager used synchronously
Browse files Browse the repository at this point in the history
Otherwise it says it does not have `__enter__` which is obvious for
advanced pythonista. Still a tiny bit clearer is likely better.

I guess this _might_ fool static type checkers, but I'm unaware of any
that would flag that.
  • Loading branch information
Carreau committed Jun 13, 2017
1 parent f2fdb63 commit f4878c3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
6 changes: 6 additions & 0 deletions trio/_core/tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ async def child(x):
await task.wait()
assert task.result.unwrap() == 20

async def test_nursery_warn_use_async_with():
with ignore_coroutine_never_awaited_warnings():
with pytest.raises(RuntimeError) as excinfo:
with _core.open_nursery() as nursery:
pass
excinfo.match(r'.*open_nursery.*use with `async with` and not `with`.')

async def test_child_crash_basic():
exc = ValueError("uh oh")
Expand Down
8 changes: 8 additions & 0 deletions trio/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ async def __aiter__(*args, **kwargs):
# Copyright © 2001-2017 Python Software Foundation; All Rights Reserved
class _AsyncGeneratorContextManager:
def __init__(self, func, args, kwds):
self._func_name = func.__name__
self._agen = func(*args, **kwds).__aiter__()

async def __aenter__(self):
Expand Down Expand Up @@ -135,6 +136,13 @@ async def __aexit__(self, type, value, traceback):
if sys.exc_info()[1] is not value:
raise

def __enter__(self):
raise RuntimeError("The function `{}` create an async context manager, use with `async with` and not `with`.".format(self._func_name))

def __exit__(self):
assert False, """Never called, but should be defined"""


def acontextmanager(func):
"""Like @contextmanager, but async."""
if not async_generator.isasyncgenfunction(func):
Expand Down

0 comments on commit f4878c3

Please sign in to comment.