mirror of
https://github.com/python/cpython.git
synced 2025-08-04 17:08:35 +00:00
gh-128398: improve error messages when incorrectly using with
and async with
(#132218)
Improve the error message with a suggestion when an object supporting the synchronous (resp. asynchronous) context manager protocol is entered using `async with` (resp. `with`) instead of `with` (resp. `async with`).
This commit is contained in:
parent
95800fe6e7
commit
8a9c6c4d16
10 changed files with 211 additions and 47 deletions
|
@ -75,9 +75,17 @@ class IsolatedAsyncioTestCase(TestCase):
|
|||
enter = cls.__aenter__
|
||||
exit = cls.__aexit__
|
||||
except AttributeError:
|
||||
raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
|
||||
f"not support the asynchronous context manager protocol"
|
||||
) from None
|
||||
msg = (f"'{cls.__module__}.{cls.__qualname__}' object does "
|
||||
"not support the asynchronous context manager protocol")
|
||||
try:
|
||||
cls.__enter__
|
||||
cls.__exit__
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
msg += (" but it supports the context manager protocol. "
|
||||
"Did you mean to use enterContext()?")
|
||||
raise TypeError(msg) from None
|
||||
result = await enter(cm)
|
||||
self.addAsyncCleanup(exit, cm, None, None, None)
|
||||
return result
|
||||
|
|
|
@ -111,8 +111,17 @@ def _enter_context(cm, addcleanup):
|
|||
enter = cls.__enter__
|
||||
exit = cls.__exit__
|
||||
except AttributeError:
|
||||
raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
|
||||
f"not support the context manager protocol") from None
|
||||
msg = (f"'{cls.__module__}.{cls.__qualname__}' object does "
|
||||
"not support the context manager protocol")
|
||||
try:
|
||||
cls.__aenter__
|
||||
cls.__aexit__
|
||||
except AttributeError:
|
||||
pass
|
||||
else:
|
||||
msg += (" but it supports the asynchronous context manager "
|
||||
"protocol. Did you mean to use enterAsyncContext()?")
|
||||
raise TypeError(msg) from None
|
||||
result = enter(cm)
|
||||
addcleanup(exit, cm, None, None, None)
|
||||
return result
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue