@@ -818,33 +818,31 @@ definition:
818
818
>>> import logging
819
819
>>> logging.basicConfig(level = logging.INFO )
820
820
>>> @ contextmanager
821
- ... def track_entry_and_exit ():
822
- ... logging.info(' Entry ' )
821
+ ... def track_entry_and_exit (name ):
822
+ ... logging.info(' Entering: {} ' .format(name) )
823
823
... yield
824
- ... logging.info(' Exit ' )
824
+ ... logging.info(' Exiting: {} ' .format(name) )
825
825
826
826
Formerly, this would have only been usable as a context manager:
827
827
828
- >>> with track_entry_and_exit():
828
+ >>> with track_entry_and_exit(' widget loader ' ):
829
829
... print (' Some time consuming activity goes here' )
830
+ ... load_widget()
830
831
831
832
Now, it can be used as a decorator as well:
832
833
833
- >>> @ track_entry_and_exit
834
+ >>> @ track_entry_and_exit( ' widget loader ' )
834
835
... def activity ():
835
- ... print (' Some time consuming activity goes here'
836
+ ... print (' Some time consuming activity goes here' )
837
+ ... load_widget()
836
838
837
839
Trying to fulfill two roles at once places some limitations on the technique.
838
840
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.
848
846
849
847
(Contributed by Michael Foord in :issue: `9110 `.)
850
848
0 commit comments