GH-101100: Fix reference warnings for `__enter__ and __exit__` (#110112)

This commit is contained in:
Adam Turner 2023-10-19 16:05:17 +01:00 committed by GitHub
parent da99133710
commit 63acf78d71
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 58 additions and 58 deletions

View file

@ -239,7 +239,7 @@ Glossary
context manager context manager
An object which controls the environment seen in a :keyword:`with` An object which controls the environment seen in a :keyword:`with`
statement by defining :meth:`__enter__` and :meth:`__exit__` methods. statement by defining :meth:`~object.__enter__` and :meth:`~object.__exit__` methods.
See :pep:`343`. See :pep:`343`.
context variable context variable

View file

@ -45,7 +45,7 @@ Functions and classes provided:
This function is a :term:`decorator` that can be used to define a factory This function is a :term:`decorator` that can be used to define a factory
function for :keyword:`with` statement context managers, without needing to function for :keyword:`with` statement context managers, without needing to
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. create a class or separate :meth:`~object.__enter__` and :meth:`~object.__exit__` methods.
While many objects natively support use in with statements, sometimes a While many objects natively support use in with statements, sometimes a
resource needs to be managed that isn't a context manager in its own right, resource needs to be managed that isn't a context manager in its own right,
@ -515,7 +515,7 @@ Functions and classes provided:
# the with statement, even if attempts to open files later # the with statement, even if attempts to open files later
# in the list raise an exception # in the list raise an exception
The :meth:`__enter__` method returns the :class:`ExitStack` instance, and The :meth:`~object.__enter__` method returns the :class:`ExitStack` instance, and
performs no additional operations. performs no additional operations.
Each instance maintains a stack of registered callbacks that are called in Each instance maintains a stack of registered callbacks that are called in
@ -543,9 +543,9 @@ Functions and classes provided:
.. method:: enter_context(cm) .. method:: enter_context(cm)
Enters a new context manager and adds its :meth:`__exit__` method to Enters a new context manager and adds its :meth:`~object.__exit__` method to
the callback stack. The return value is the result of the context the callback stack. The return value is the result of the context
manager's own :meth:`__enter__` method. manager's own :meth:`~object.__enter__` method.
These context managers may suppress exceptions just as they normally These context managers may suppress exceptions just as they normally
would if used directly as part of a :keyword:`with` statement. would if used directly as part of a :keyword:`with` statement.
@ -556,18 +556,18 @@ Functions and classes provided:
.. method:: push(exit) .. method:: push(exit)
Adds a context manager's :meth:`__exit__` method to the callback stack. Adds a context manager's :meth:`~object.__exit__` method to the callback stack.
As ``__enter__`` is *not* invoked, this method can be used to cover As ``__enter__`` is *not* invoked, this method can be used to cover
part of an :meth:`__enter__` implementation with a context manager's own part of an :meth:`~object.__enter__` implementation with a context manager's own
:meth:`__exit__` method. :meth:`~object.__exit__` method.
If passed an object that is not a context manager, this method assumes If passed an object that is not a context manager, this method assumes
it is a callback with the same signature as a context manager's it is a callback with the same signature as a context manager's
:meth:`__exit__` method and adds it directly to the callback stack. :meth:`~object.__exit__` method and adds it directly to the callback stack.
By returning true values, these callbacks can suppress exceptions the By returning true values, these callbacks can suppress exceptions the
same way context manager :meth:`__exit__` methods can. same way context manager :meth:`~object.__exit__` methods can.
The passed in object is returned from the function, allowing this The passed in object is returned from the function, allowing this
method to be used as a function decorator. method to be used as a function decorator.
@ -714,7 +714,7 @@ Cleaning up in an ``__enter__`` implementation
As noted in the documentation of :meth:`ExitStack.push`, this As noted in the documentation of :meth:`ExitStack.push`, this
method can be useful in cleaning up an already allocated resource if later method can be useful in cleaning up an already allocated resource if later
steps in the :meth:`__enter__` implementation fail. steps in the :meth:`~object.__enter__` implementation fail.
Here's an example of doing this for a context manager that accepts resource Here's an example of doing this for a context manager that accepts resource
acquisition and release functions, along with an optional validation function, acquisition and release functions, along with an optional validation function,
@ -871,7 +871,7 @@ And also as a function decorator::
Note that there is one additional limitation when using context managers Note that there is one additional limitation when using context managers
as function decorators: there's no way to access the return value of as function decorators: there's no way to access the return value of
:meth:`__enter__`. If that value is needed, then it is still necessary to use :meth:`~object.__enter__`. If that value is needed, then it is still necessary to use
an explicit ``with`` statement. an explicit ``with`` statement.
.. seealso:: .. seealso::

View file

@ -4857,7 +4857,7 @@ before the statement body is executed and exited when the statement ends:
The exception passed in should never be reraised explicitly - instead, this The exception passed in should never be reraised explicitly - instead, this
method should return a false value to indicate that the method completed method should return a false value to indicate that the method completed
successfully and does not want to suppress the raised exception. This allows successfully and does not want to suppress the raised exception. This allows
context management code to easily detect whether or not an :meth:`__exit__` context management code to easily detect whether or not an :meth:`~object.__exit__`
method has actually failed. method has actually failed.
Python defines several context managers to support easy thread synchronisation, Python defines several context managers to support easy thread synchronisation,

View file

@ -1043,7 +1043,7 @@ The :mod:`test.support` module defines the following classes:
:const:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file :const:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
creation. creation.
On both platforms, the old value is restored by :meth:`__exit__`. On both platforms, the old value is restored by :meth:`~object.__exit__`.
.. class:: SaveSignals() .. class:: SaveSignals()

View file

@ -2531,8 +2531,8 @@ are closed properly and is becoming common::
f.write('something') f.write('something')
The issue is that even if you mock out the call to :func:`open` it is the The issue is that even if you mock out the call to :func:`open` it is the
*returned object* that is used as a context manager (and has :meth:`__enter__` and *returned object* that is used as a context manager (and has :meth:`~object.__enter__` and
:meth:`__exit__` called). :meth:`~object.__exit__` called).
Mocking context managers with a :class:`MagicMock` is common enough and fiddly Mocking context managers with a :class:`MagicMock` is common enough and fiddly
enough that a helper function is useful. :: enough that a helper function is useful. ::

View file

@ -489,37 +489,37 @@ The execution of the :keyword:`with` statement with one "item" proceeds as follo
#. The context expression (the expression given in the #. The context expression (the expression given in the
:token:`~python-grammar:with_item`) is evaluated to obtain a context manager. :token:`~python-grammar:with_item`) is evaluated to obtain a context manager.
#. The context manager's :meth:`__enter__` is loaded for later use. #. The context manager's :meth:`~object.__enter__` is loaded for later use.
#. The context manager's :meth:`__exit__` is loaded for later use. #. The context manager's :meth:`~object.__exit__` is loaded for later use.
#. The context manager's :meth:`__enter__` method is invoked. #. The context manager's :meth:`~object.__enter__` method is invoked.
#. If a target was included in the :keyword:`with` statement, the return value #. If a target was included in the :keyword:`with` statement, the return value
from :meth:`__enter__` is assigned to it. from :meth:`~object.__enter__` is assigned to it.
.. note:: .. note::
The :keyword:`with` statement guarantees that if the :meth:`__enter__` The :keyword:`with` statement guarantees that if the :meth:`~object.__enter__`
method returns without an error, then :meth:`__exit__` will always be method returns without an error, then :meth:`~object.__exit__` will always be
called. Thus, if an error occurs during the assignment to the target list, called. Thus, if an error occurs during the assignment to the target list,
it will be treated the same as an error occurring within the suite would it will be treated the same as an error occurring within the suite would
be. See step 7 below. be. See step 7 below.
#. The suite is executed. #. The suite is executed.
#. The context manager's :meth:`__exit__` method is invoked. If an exception #. The context manager's :meth:`~object.__exit__` method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are passed as caused the suite to be exited, its type, value, and traceback are passed as
arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are arguments to :meth:`~object.__exit__`. Otherwise, three :const:`None` arguments are
supplied. supplied.
If the suite was exited due to an exception, and the return value from the If the suite was exited due to an exception, and the return value from the
:meth:`__exit__` method was false, the exception is reraised. If the return :meth:`~object.__exit__` method was false, the exception is reraised. If the return
value was true, the exception is suppressed, and execution continues with the value was true, the exception is suppressed, and execution continues with the
statement following the :keyword:`with` statement. statement following the :keyword:`with` statement.
If the suite was exited for any reason other than an exception, the return If the suite was exited for any reason other than an exception, the return
value from :meth:`__exit__` is ignored, and execution proceeds at the normal value from :meth:`~object.__exit__` is ignored, and execution proceeds at the normal
location for the kind of exit that was taken. location for the kind of exit that was taken.
The following code:: The following code::

View file

@ -2939,7 +2939,7 @@ For more information on context managers, see :ref:`typecontextmanager`.
(i.e., prevent it from being propagated), it should return a true value. (i.e., prevent it from being propagated), it should return a true value.
Otherwise, the exception will be processed normally upon exit from this method. Otherwise, the exception will be processed normally upon exit from this method.
Note that :meth:`__exit__` methods should not reraise the passed-in exception; Note that :meth:`~object.__exit__` methods should not reraise the passed-in exception;
this is the caller's responsibility. this is the caller's responsibility.
@ -3257,12 +3257,12 @@ Asynchronous context managers can be used in an :keyword:`async with` statement.
.. method:: object.__aenter__(self) .. method:: object.__aenter__(self)
Semantically similar to :meth:`__enter__`, the only Semantically similar to :meth:`~object.__enter__`, the only
difference being that it must return an *awaitable*. difference being that it must return an *awaitable*.
.. method:: object.__aexit__(self, exc_type, exc_value, traceback) .. method:: object.__aexit__(self, exc_type, exc_value, traceback)
Semantically similar to :meth:`__exit__`, the only Semantically similar to :meth:`~object.__exit__`, the only
difference being that it must return an *awaitable*. difference being that it must return an *awaitable*.
An example of an asynchronous context manager class:: An example of an asynchronous context manager class::

View file

@ -575,15 +575,15 @@ structure is::
with-block with-block
The expression is evaluated, and it should result in an object that supports the The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__` context management protocol (that is, has :meth:`~object.__enter__` and :meth:`~object.__exit__`
methods. methods.
The object's :meth:`__enter__` is called before *with-block* is executed and The object's :meth:`~object.__enter__` is called before *with-block* is executed and
therefore can run set-up code. It also may return a value that is bound to the therefore can run set-up code. It also may return a value that is bound to the
name *variable*, if given. (Note carefully that *variable* is *not* assigned name *variable*, if given. (Note carefully that *variable* is *not* assigned
the result of *expression*.) the result of *expression*.)
After execution of the *with-block* is finished, the object's :meth:`__exit__` After execution of the *with-block* is finished, the object's :meth:`~object.__exit__`
method is called, even if the block raised an exception, and can therefore run method is called, even if the block raised an exception, and can therefore run
clean-up code. clean-up code.
@ -609,7 +609,7 @@ part-way through the block.
.. note:: .. note::
In this case, *f* is the same object created by :func:`open`, because In this case, *f* is the same object created by :func:`open`, because
:meth:`file.__enter__` returns *self*. :meth:`~object.__enter__` returns *self*.
The :mod:`threading` module's locks and condition variables also support the The :mod:`threading` module's locks and condition variables also support the
':keyword:`with`' statement:: ':keyword:`with`' statement::
@ -652,10 +652,10 @@ underlying implementation and should keep reading.
A high-level explanation of the context management protocol is: A high-level explanation of the context management protocol is:
* The expression is evaluated and should result in an object called a "context * The expression is evaluated and should result in an object called a "context
manager". The context manager must have :meth:`__enter__` and :meth:`__exit__` manager". The context manager must have :meth:`~object.__enter__` and :meth:`~object.__exit__`
methods. methods.
* The context manager's :meth:`__enter__` method is called. The value returned * The context manager's :meth:`~object.__enter__` method is called. The value returned
is assigned to *VAR*. If no ``'as VAR'`` clause is present, the value is simply is assigned to *VAR*. If no ``'as VAR'`` clause is present, the value is simply
discarded. discarded.
@ -669,7 +669,7 @@ A high-level explanation of the context management protocol is:
if you do the author of the code containing the ':keyword:`with`' statement will if you do the author of the code containing the ':keyword:`with`' statement will
never realize anything went wrong. never realize anything went wrong.
* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still * If *BLOCK* didn't raise an exception, the :meth:`~object.__exit__` method is still
called, but *type*, *value*, and *traceback* are all ``None``. called, but *type*, *value*, and *traceback* are all ``None``.
Let's think through an example. I won't present detailed code but will only Let's think through an example. I won't present detailed code but will only
@ -703,7 +703,7 @@ rolled back if there's an exception. Here's the basic interface for
def rollback (self): def rollback (self):
"Rolls back current transaction" "Rolls back current transaction"
The :meth:`__enter__` method is pretty easy, having only to start a new The :meth:`~object.__enter__` method is pretty easy, having only to start a new
transaction. For this application the resulting cursor object would be a useful transaction. For this application the resulting cursor object would be a useful
result, so the method will return it. The user can then add ``as cursor`` to result, so the method will return it. The user can then add ``as cursor`` to
their ':keyword:`with`' statement to bind the cursor to a variable name. :: their ':keyword:`with`' statement to bind the cursor to a variable name. ::
@ -715,7 +715,7 @@ their ':keyword:`with`' statement to bind the cursor to a variable name. ::
cursor = self.cursor() cursor = self.cursor()
return cursor return cursor
The :meth:`__exit__` method is the most complicated because it's where most of The :meth:`~object.__exit__` method is the most complicated because it's where most of
the work has to be done. The method has to check if an exception occurred. If the work has to be done. The method has to check if an exception occurred. If
there was no exception, the transaction is committed. The transaction is rolled there was no exception, the transaction is committed. The transaction is rolled
back if there was an exception. back if there was an exception.
@ -748,10 +748,10 @@ are useful for writing objects for use with the ':keyword:`with`' statement.
The decorator is called :func:`contextmanager`, and lets you write a single The decorator is called :func:`contextmanager`, and lets you write a single
generator function instead of defining a new class. The generator should yield generator function instead of defining a new class. The generator should yield
exactly one value. The code up to the :keyword:`yield` will be executed as the exactly one value. The code up to the :keyword:`yield` will be executed as the
:meth:`__enter__` method, and the value yielded will be the method's return :meth:`~object.__enter__` method, and the value yielded will be the method's return
value that will get bound to the variable in the ':keyword:`with`' statement's value that will get bound to the variable in the ':keyword:`with`' statement's
:keyword:`!as` clause, if any. The code after the :keyword:`yield` will be :keyword:`!as` clause, if any. The code after the :keyword:`yield` will be
executed in the :meth:`__exit__` method. Any exception raised in the block will executed in the :meth:`~object.__exit__` method. Any exception raised in the block will
be raised by the :keyword:`!yield` statement. be raised by the :keyword:`!yield` statement.
Our database example from the previous section could be written using this Our database example from the previous section could be written using this

View file

@ -269,15 +269,15 @@ structure is::
with-block with-block
The expression is evaluated, and it should result in an object that supports the The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__` context management protocol (that is, has :meth:`~object.__enter__` and :meth:`~object.__exit__`
methods). methods).
The object's :meth:`__enter__` is called before *with-block* is executed and The object's :meth:`~object.__enter__` is called before *with-block* is executed and
therefore can run set-up code. It also may return a value that is bound to the therefore can run set-up code. It also may return a value that is bound to the
name *variable*, if given. (Note carefully that *variable* is *not* assigned name *variable*, if given. (Note carefully that *variable* is *not* assigned
the result of *expression*.) the result of *expression*.)
After execution of the *with-block* is finished, the object's :meth:`__exit__` After execution of the *with-block* is finished, the object's :meth:`~object.__exit__`
method is called, even if the block raised an exception, and can therefore run method is called, even if the block raised an exception, and can therefore run
clean-up code. clean-up code.
@ -296,7 +296,7 @@ part-way through the block.
.. note:: .. note::
In this case, *f* is the same object created by :func:`open`, because In this case, *f* is the same object created by :func:`open`, because
:meth:`file.__enter__` returns *self*. :meth:`~object.__enter__` returns *self*.
The :mod:`threading` module's locks and condition variables also support the The :mod:`threading` module's locks and condition variables also support the
':keyword:`with`' statement:: ':keyword:`with`' statement::
@ -339,16 +339,16 @@ underlying implementation and should keep reading.
A high-level explanation of the context management protocol is: A high-level explanation of the context management protocol is:
* The expression is evaluated and should result in an object called a "context * The expression is evaluated and should result in an object called a "context
manager". The context manager must have :meth:`__enter__` and :meth:`__exit__` manager". The context manager must have :meth:`~object.__enter__` and :meth:`~object.__exit__`
methods. methods.
* The context manager's :meth:`__enter__` method is called. The value returned * The context manager's :meth:`~object.__enter__` method is called. The value returned
is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply is assigned to *VAR*. If no ``as VAR`` clause is present, the value is simply
discarded. discarded.
* The code in *BLOCK* is executed. * The code in *BLOCK* is executed.
* If *BLOCK* raises an exception, the context manager's :meth:`__exit__` method * If *BLOCK* raises an exception, the context manager's :meth:`~object.__exit__` method
is called with three arguments, the exception details (``type, value, traceback``, is called with three arguments, the exception details (``type, value, traceback``,
the same values returned by :func:`sys.exc_info`, which can also be ``None`` the same values returned by :func:`sys.exc_info`, which can also be ``None``
if no exception occurred). The method's return value controls whether an exception if no exception occurred). The method's return value controls whether an exception
@ -357,7 +357,7 @@ A high-level explanation of the context management protocol is:
if you do the author of the code containing the ':keyword:`with`' statement will if you do the author of the code containing the ':keyword:`with`' statement will
never realize anything went wrong. never realize anything went wrong.
* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still * If *BLOCK* didn't raise an exception, the :meth:`~object.__exit__` method is still
called, but *type*, *value*, and *traceback* are all ``None``. called, but *type*, *value*, and *traceback* are all ``None``.
Let's think through an example. I won't present detailed code but will only Let's think through an example. I won't present detailed code but will only
@ -391,7 +391,7 @@ rolled back if there's an exception. Here's the basic interface for
def rollback(self): def rollback(self):
"Rolls back current transaction" "Rolls back current transaction"
The :meth:`__enter__` method is pretty easy, having only to start a new The :meth:`~object.__enter__` method is pretty easy, having only to start a new
transaction. For this application the resulting cursor object would be a useful transaction. For this application the resulting cursor object would be a useful
result, so the method will return it. The user can then add ``as cursor`` to result, so the method will return it. The user can then add ``as cursor`` to
their ':keyword:`with`' statement to bind the cursor to a variable name. :: their ':keyword:`with`' statement to bind the cursor to a variable name. ::
@ -403,7 +403,7 @@ their ':keyword:`with`' statement to bind the cursor to a variable name. ::
cursor = self.cursor() cursor = self.cursor()
return cursor return cursor
The :meth:`__exit__` method is the most complicated because it's where most of The :meth:`~object.__exit__` method is the most complicated because it's where most of
the work has to be done. The method has to check if an exception occurred. If the work has to be done. The method has to check if an exception occurred. If
there was no exception, the transaction is committed. The transaction is rolled there was no exception, the transaction is committed. The transaction is rolled
back if there was an exception. back if there was an exception.
@ -436,10 +436,10 @@ are useful when writing objects for use with the ':keyword:`with`' statement.
The decorator is called :func:`contextmanager`, and lets you write a single The decorator is called :func:`contextmanager`, and lets you write a single
generator function instead of defining a new class. The generator should yield generator function instead of defining a new class. The generator should yield
exactly one value. The code up to the :keyword:`yield` will be executed as the exactly one value. The code up to the :keyword:`yield` will be executed as the
:meth:`__enter__` method, and the value yielded will be the method's return :meth:`~object.__enter__` method, and the value yielded will be the method's return
value that will get bound to the variable in the ':keyword:`with`' statement's value that will get bound to the variable in the ':keyword:`with`' statement's
:keyword:`!as` clause, if any. The code after the :keyword:`!yield` will be :keyword:`!as` clause, if any. The code after the :keyword:`!yield` will be
executed in the :meth:`__exit__` method. Any exception raised in the block will executed in the :meth:`~object.__exit__` method. Any exception raised in the block will
be raised by the :keyword:`!yield` statement. be raised by the :keyword:`!yield` statement.
Using this decorator, our database example from the previous section Using this decorator, our database example from the previous section
@ -1737,7 +1737,7 @@ Optimizations
(Contributed by Antoine Pitrou.) Memory usage is reduced (Contributed by Antoine Pitrou.) Memory usage is reduced
by using pymalloc for the Unicode string's data. by using pymalloc for the Unicode string's data.
* The ``with`` statement now stores the :meth:`__exit__` method on the stack, * The ``with`` statement now stores the :meth:`~object.__exit__` method on the stack,
producing a small speedup. (Implemented by Jeffrey Yasskin.) producing a small speedup. (Implemented by Jeffrey Yasskin.)
* To reduce memory usage, the garbage collector will now clear internal * To reduce memory usage, the garbage collector will now clear internal

View file

@ -930,8 +930,8 @@ Optimizations
Several performance enhancements have been added: Several performance enhancements have been added:
* A new opcode was added to perform the initial setup for * A new opcode was added to perform the initial setup for
:keyword:`with` statements, looking up the :meth:`__enter__` and :keyword:`with` statements, looking up the :meth:`~object.__enter__` and
:meth:`__exit__` methods. (Contributed by Benjamin Peterson.) :meth:`~object.__exit__` methods. (Contributed by Benjamin Peterson.)
* The garbage collector now performs better for one common usage * The garbage collector now performs better for one common usage
pattern: when many objects are being allocated without deallocating pattern: when many objects are being allocated without deallocating
@ -2449,13 +2449,13 @@ that may require changes to your code:
(Changed by Eric Smith; :issue:`5920`.) (Changed by Eric Smith; :issue:`5920`.)
* Because of an optimization for the :keyword:`with` statement, the special * Because of an optimization for the :keyword:`with` statement, the special
methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's methods :meth:`~object.__enter__` and :meth:`~object.__exit__` must belong to the object's
type, and cannot be directly attached to the object's instance. This type, and cannot be directly attached to the object's instance. This
affects new-style classes (derived from :class:`object`) and C extension affects new-style classes (derived from :class:`object`) and C extension
types. (:issue:`6101`.) types. (:issue:`6101`.)
* Due to a bug in Python 2.6, the *exc_value* parameter to * Due to a bug in Python 2.6, the *exc_value* parameter to
:meth:`__exit__` methods was often the string representation of the :meth:`~object.__exit__` methods was often the string representation of the
exception, not an instance. This was fixed in 2.7, so *exc_value* exception, not an instance. This was fixed in 2.7, so *exc_value*
will be an instance as expected. (Fixed by Florent Xicluna; will be an instance as expected. (Fixed by Florent Xicluna;
:issue:`7853`.) :issue:`7853`.)

View file

@ -274,7 +274,7 @@ Co-authored-by: Tim Peters <tim.peters@gmail.com>
Only handle asynchronous exceptions and requests to drop the GIL when Only handle asynchronous exceptions and requests to drop the GIL when
returning from a call or on the back edges of loops. Makes sure that returning from a call or on the back edges of loops. Makes sure that
:meth:`__exit__` is always called in with statements, even for interrupts. :meth:`~object.__exit__` is always called in with statements, even for interrupts.
.. ..