Skip to content

Commit 9743e4f

Browse files
committed
Improve the ContextDecorator example.
1 parent f68fa05 commit 9743e4f

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

Doc/whatsnew/3.2.rst

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -818,33 +818,31 @@ definition:
818818
>>> import logging
819819
>>> logging.basicConfig(level=logging.INFO)
820820
>>> @contextmanager
821-
... def track_entry_and_exit():
822-
... logging.info('Entry')
821+
... def track_entry_and_exit(name):
822+
... logging.info('Entering: {}'.format(name))
823823
... yield
824-
... logging.info('Exit')
824+
... logging.info('Exiting: {}'.format(name))
825825

826826
Formerly, this would have only been usable as a context manager:
827827

828-
>>> with track_entry_and_exit():
828+
>>> with track_entry_and_exit('widget loader'):
829829
... print('Some time consuming activity goes here')
830+
... load_widget()
830831

831832
Now, it can be used as a decorator as well:
832833

833-
>>> @track_entry_and_exit
834+
>>> @track_entry_and_exit('widget loader')
834835
... def activity():
835-
... print('Some time consuming activity goes here'
836+
... print('Some time consuming activity goes here')
837+
... load_widget()
836838

837839
Trying to fulfill two roles at once places some limitations on the technique.
838840
Context managers normally have the flexibility to return an argument usable by
839-
the :keyword:`with`-statement, and function decorators can be constructed to
840-
accept arguments or to know the name of the function they are enclosing. Since
841-
those features of context managers and function decorators are not overlapping,
842-
those features are not supported.
843-
844-
In the above example, there is not a clean way for the
845-
:func:`track_entry_and_exit` decorator to know the name of the enclosed
846-
function. Likewise, the *track_entry_and_exit* context manager does not have a
847-
way to return a logging instance for use in the body of enclosed statements.
841+
the :keyword:`with`-statement, but there is no parallel for function decorators.
842+
843+
In the above example, there is not a clean way for the *track_entry_and_exit*
844+
context manager does not have a way to return a logging instance for use in the
845+
body of enclosed statements.
848846

849847
(Contributed by Michael Foord in :issue:`9110`.)
850848

0 commit comments

Comments
 (0)