Vc.i|dZddlZddlZddlZddlZddlmZddlmZddl m Z m Z gdZ Gddej ZGd d ej ZGd d eZGd deZGddZGddeeeZGddeeeZdZdZGddeZGddeZGddeZGddeZGdd eZGd!d"eZGd#d$ZGd%d&eeZGd'd(eeZ Gd)d*eeZ!Gd+d,eZ"dS)-z4Utilities for with-statement contexts. See PEP 343.N)dequewraps) MethodType GenericAlias)asynccontextmanagercontextmanagerclosing nullcontextAbstractContextManagerAbstractAsyncContextManagerAsyncExitStackContextDecorator ExitStackredirect_stdoutredirect_stderrsuppressaclosingchdircdeZdZdZeeZdZej dZ edZ dS)r z,An abstract base class for context managers.c|Sz0Return `self` upon entering the runtime context.selfs #/usr/lib64/python3.11/contextlib.py __enter__z AbstractContextManager.__enter__s cdSz9Raise any exception triggered within the runtime context.Nrrexc_type exc_value tracebacks r__exit__zAbstractContextManager.__exit__s trcN|turtj|ddStS)Nrr%)r _collections_abc_check_methodsNotImplementedclsCs r__subclasshook__z'AbstractContextManager.__subclasshook__ s, ( ( O#21k:NN NrN) __name__ __module__ __qualname____doc__ classmethodr__class_getitem__rabcabstractmethodr%r-rrrr r ss66# L11 [rr cdeZdZdZeeZdZej dZ edZ dS)r z9An abstract base class for asynchronous context managers.c K|Srrrs r __aenter__z&AbstractAsyncContextManager.__aenter__-s  rc KdSr rr!s r __aexit__z%AbstractAsyncContextManager.__aexit__1s trcN|turtj|ddStS)Nr8r:)r r'r(r)r*s rr-z,AbstractAsyncContextManager.__subclasshook__6s6 - - @#21l3>@@ @rN) r.r/r0r1r2rr3r8r4r5r:r-rrrr r 'ssCC# L11 [rr ceZdZdZdZdZdS)rzJA base class or mixin that enables context managers to work as decorators.c|S)a6Return a recreated instance of self. Allows an otherwise one-shot context manager like _GeneratorContextManager to support use as a decorator via implicit recreation. This is a private interface just for _GeneratorContextManager. See issue #11647 for details. rrs r _recreate_cmzContextDecorator._recreate_cmAs  rc@tfd}|S)Ncp5|i|cdddS#1swxYwYdSNr>argskwdsfuncrs rinnerz(ContextDecorator.__call__..innerNs""$$ + +tT*T** + + + + + + + + + + + + + + + + + +s +//rrrFrGs`` r__call__zContextDecorator.__call__Ms9 t + + + + +  + rNr.r/r0r1r>rIrrrrr>s8PP   rrceZdZdZdZdZdS)AsyncContextDecoratorzPA base class or mixin that enables async context managers to work as decorators.c|S)z-Return a recreated instance of self. rrs rr>z"AsyncContextDecorator._recreate_cmXs  rc@tfd}|S)NcK4d{V|i|d{Vcdddd{VS#1d{VswxYwYdSrArBrCs rrGz-AsyncContextDecorator.__call__..inner^s((** 1 1 1 1 1 1 1 1!T40400000000 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1s? A  A rrHs`` rrIzAsyncContextDecorator.__call__]s9 t 1 1 1 1 1  1 rNrJrrrrLrLUs8VV rrLceZdZdZdZdZdS)_GeneratorContextManagerBasezBShared functionality for @contextmanager and @asynccontextmanager.c||i||_|||c|_|_|_t |dd}|t |j}||_dS)Nr1)genrFrDrEgetattrtyper1)rrFrDrEdocs r__init__z%_GeneratorContextManagerBase.__init__hs`4&&&*.d' 49didIt,,  %t**$C rcN||j|j|jSrA) __class__rFrDrErs rr>z)_GeneratorContextManagerBase._recreate_cmvs ~~diDI>>>rN)r.r/r0r1rWr>rrrrQrQes8LL?????rrQceZdZdZdZdZdS)_GeneratorContextManagerz%Helper for @contextmanager decorator.ct|`|`|` t|jS#t $rt ddwxYwNzgenerator didn't yield)rDrErFnextrS StopIteration RuntimeErrorrs rrz"_GeneratorContextManager.__enter__sU Ity$) C>> ! C C C788d B Cs7c|5 t|jtd#t$rYdSwxYw| |} |j|||n#t$r}||ucYd}~Sd}~wt$rB}||ur ||_Yd}~dSt |tr|j|ur ||_Yd}~dSd}~wt$r}||ur||_Yd}~dSd}~wwxYwtd)Ngenerator didn't stopFz#generator didn't stop after throw()) r^rSr`r_throw __traceback__ isinstance __cause__ BaseExceptionrtypvaluer$excs rr%z!_GeneratorContextManager.__exit__s 0 F <TX##:;;;!   uu   # sE95555  ( ( (%'''''''   %<!(1C% 55555um44! .!)2C% 55555   e#$-!uuuuu DEE EsN' 55A"" C#,A5/C#5 C# B?%B?>B?? C# CC#N)r.r/r0r1rr%rrrr[r[}sB 0/CCC1F1F1F1F1Frr[ceZdZdZdZdZdS)_AsyncGeneratorContextManagerz*Helper for @asynccontextmanager decorator.cK|`|`|` t|jd{VS#t $rt ddwxYwr])rDrErFanextrSStopAsyncIterationr`rs rr8z(_AsyncGeneratorContextManager.__aenter__sk Ity$) Ctx(((((( (! C C C788d B Cs$?cK|; t|jd{Vtd#t$rYdSwxYw| |} |j|||d{Vnv#t$r}||ucYd}~Sd}~wt$r;}||urYd}~dSt |t tfr|j|urYd}~dSd}~wt$r}||urYd}~dSd}~wwxYwtd)NrbFz$generator didn't stop after athrow()) rorSr`rpathrowrer_rfrgrhs rr:z'_AsyncGeneratorContextManager.__aexit__s - G <DHoo%%%%%%%##:;;;&   uu    hooc5)<<<<<<<<<<% ( ( (%'''''''   %<! 55555u}6H&IJJ! .!!55555   e#uuuuu EFF FsN/ == "A00 C#:B=C# C#C%CC C#CC#N)r.r/r0r1r8r:rrrrmrmsB 54CCC.G.G.G.G.Grrmc<tfd}|S)a@contextmanager decorator. Typical usage: @contextmanager def some_generator(): try: yield finally: This makes this: with some_generator() as : equivalent to this: try: = finally: c&t||SrA)r[rDrErFs rhelperzcontextmanager..helpers'dD999rrrFrvs` rr r s36 4[[::::[: Mrc<tfd}|S)a@asynccontextmanager decorator. Typical usage: @asynccontextmanager async def some_async_generator(): try: yield finally: This makes this: async with some_async_generator() as : equivalent to this: try: = finally: c&t||SrA)rmrus rrvz#asynccontextmanager..helper=s,T4>>>rrrws` rrr"s36 4[[????[? Mrc$eZdZdZdZdZdZdS)r a2Context to automatically close something at the end of a block. Code like this: with closing(.open()) as f: is equivalent to this: f = .open() try: finally: f.close() c||_dSrAthingrr}s rrWzclosing.__init__T  rc|jSrAr|rs rrzclosing.__enter__Vs zrc8|jdSrA)r}closerexc_infos rr%zclosing.__exit__Xs rNr.r/r0r1rWrr%rrrr r CsK rr c$eZdZdZdZdZdZdS)raAsync context manager for safely finalizing an asynchronously cleaned-up resource such as an async generator, calling its ``aclose()`` method. Code like this: async with aclosing(.fetch()) as agen: is equivalent to this: agen = .fetch() try: finally: await agen.aclose() c||_dSrAr|r~s rrWzaclosing.__init__nrrcK|jSrAr|rs rr8zaclosing.__aenter__pszrcHK|jd{VdSrA)r}aclosers rr:zaclosing.__aexit__rs2j!!!!!!!!!!!rN)r.r/r0r1rWr8r:rrrrr\sK""""""rrc$eZdZdZdZdZdZdS)_RedirectStreamNc"||_g|_dSrA) _new_target _old_targets)r new_targets rrWz_RedirectStream.__init__zs%rc|jtt|jt t|j|j|jSrA)rappendrTsys_streamsetattrrrs rrz_RedirectStream.__enter__sE   dl!;!;<<<T\4#3444rcjtt|j|jdSrA)rrrrpoprexctypeexcinstexctbs rr%z_RedirectStream.__exit__s+T\4#4#8#8#:#:;;;;;r)r.r/r0rrWrr%rrrrrvsFG    <<<<._exit_wrappers Hd #d # # # # #rrrrDrErs``` r_create_cb_wrapperz!_BaseExitStack._create_cb_wrappers. $ $ $ $ $ $ $rc,t|_dSrA)r_exit_callbacksrs rrWz_BaseExitStack.__init__s$wwrcrt|}|j|_t|_|S)z@Preserve the context stack by transferring it to a new instance.)rUrr)r new_stacks rpop_allz_BaseExitStack.pop_alls0DJJLL $($8 !$wwrct|} |j}|||n%#t$r||YnwxYw|S)aRegisters a callback with the standard __exit__ method signature. Can suppress exceptions the same way __exit__ method can. Also accepts any object with an __exit__ method (registering a call to the method instead of the object itself). )rUr% _push_cm_exitAttributeError_push_exit_callbackrexit_cb_type exit_methods rpushz_BaseExitStack.pushsu:: 2"+K   t[ 1 1 1 1  + + +  $ $T * * * * * +  s/AAct|} |j}|j}n/#t$r"t d|jd|jddwxYw||}||||S)zEnters the supplied context manager. If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. '.z6' object does not support the context manager protocolN)rUrr%r TypeErrorr/r0rrrr+_enter_exitresults r enter_contextz_BaseExitStack.enter_contexts2hh S]FLEE S S SHHH1AHHHIINR S S 2u%%% s  ,A c`|j|g|Ri|}||_|||S)z\Registers an arbitrary callback and arguments. Cannot suppress exceptions. )r __wrapped__rrrrDrErs rrz_BaseExitStack.callbacksI 0/H4HHH4HH %- !   ///rc^|||}||ddS)z;Helper to correctly register callbacks to __exit__ methods.TN)rrrrrrs rrz_BaseExitStack._push_cm_exits311"g>>    55555rTc>|j||fdSrA)rr)rris_syncs rrz"_BaseExitStack._push_exit_callback s$ ##Wh$788888rN)T)r.r/r0r1 staticmethodrrrWrrrrrrrrrrrs88''\'\ '''(&   666 999999rrc$eZdZdZdZdZdZdS)raContext manager for dynamic management of a stack of exit callbacks. For example: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception. c|SrArrs rrzExitStack.__enter__s rc |ddu}tjd fd}d}d}|jrj|j\}}|sJ ||rd}d}d}n6#tj}||d|dd}|}YnxYw|jj|r2 |dj} |d#t $r| |d_wxYw|o|S)NrcF |j}|||urdS|urn|}||_dSrA __context__new_excold_exc exc_context frame_excs r_fix_exception_contextz2ExitStack.__exit__.._fix_exception_context%S &%1 +*@F)+% &#*G   rFTNNNrrrrrrg) r exc_details received_excrsuppressed_exc pending_raisercbnew_exc_details fixed_ctxrs @rr%zExitStack.__exit__sA"1~T1 LNN1%  * * * * *  " ..2244KGRNNN .2{#5%)N$)M"4K ."%,..&&q'9;q>JJJ $ - " .   (N6 !!n$    -6 A* ..s A""1B"B77Cc4|ddddSz%Immediately unwind the context stack.N)r%rs rrzExitStack.closePs dD$'''''rN)r.r/r0r1rr%rrrrrrsL//////b(((((rrcheZdZdZedZedZdZdZdZ dZ dZ d Z d Z d S) raAsync context manager for dynamic management of a stack of exit callbacks. For example: async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) for i in range(5)] # All opened connections will automatically be released at the # end of the async with statement, even if attempts to open a # connection later in the list raise an exception. c"t||SrArrs r_create_async_exit_wrapperz)AsyncExitStack._create_async_exit_wrappercrrcfd}|S)Nc(Kid{VdSrArrs rrz>AsyncExitStack._create_async_cb_wrapper.._exit_wrapperis4(D)D)) ) ) ) ) ) ) ) ) )rrrs``` r_create_async_cb_wrapperz'AsyncExitStack._create_async_cb_wrappergs. * * * * * * *rcKt|} |j}|j}n/#t$r"t d|jd|jddwxYw||d{V}||||S)zEnters the supplied async context manager. If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method. rrzC' object does not support the asynchronous context manager protocolN)rUr8r:rrr/r0_push_async_cm_exitrs renter_async_contextz"AsyncExitStack.enter_async_contextms 2hh '^FMEE ' ' 'UUU1AUUU"& ' 'vbzz!!!!!!   U+++ s ",Act|} |j}|||n&#t$r||dYnwxYw|S)a#Registers a coroutine function with the standard __aexit__ method signature. Can suppress exceptions the same way __aexit__ method can. Also accepts any object with an __aexit__ method (registering a call to the method instead of the object itself). F)rUr:rrrrs rpush_async_exitzAsyncExitStack.push_async_exitsw:: 8",K  $ $T; 7 7 7 7  2 2 2  $ $T5 1 1 1 1 1 2  s/ AAcb|j|g|Ri|}||_||d|S)zfRegisters an arbitrary coroutine function and arguments. Cannot suppress exceptions. F)rrrrs rpush_async_callbackz"AsyncExitStack.push_async_callbacksK 65hNNNNNN %- !   666rcDK|dddd{VdSr)r:rs rrzAsyncExitStack.acloses4nnT4...........rc^|||}||ddS)zLHelper to correctly register coroutine function to __aexit__ method.FN)rrrs rrz"AsyncExitStack._push_async_cm_exits577GDD    66666rc K|SrArrs rr8zAsyncExitStack.__aenter__s  rc K|ddu}tjd fd}d}d}|jrv|j\}} |r||}n ||d{V}|rd}d}d}n6#tj} || d|dd}| }YnxYw|jv|r2 |dj} |d#t $r| |d_wxYw|o|S)NrrcF |j}|||urdS|urn|}||_dSrArrs rrz8AsyncExitStack.__aexit__.._fix_exception_contextrrFTrr) rrrrrrrr cb_suppressrrrs @rr:zAsyncExitStack.__aexit__si"1~T1 LNN1%  * * * * *  " ..2244KGR .9"$"k"2KK(*K(8"8"8"8"8"8"8K5%)N$)M"4K ."%,..&&q'9;q>JJJ $ - #" .$   (N6 !!n$    -6 A* ..sA001B#0CCN)r.r/r0r1rrrrrrrrr8r:rrrrrVs  ''\'\ $$   ///777 3/3/3/3/3/rrc2eZdZdZddZdZdZdZdZdS) r aOContext manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager: cm = optional_cm if condition else nullcontext() with cm: # Perform operation, using optional_cm if condition is True Nc||_dSrA enter_result)rrs rrWznullcontext.__init__s(rc|jSrArrs rrznullcontext.__enter__s   rcdSrArrexcinfos rr%znullcontext.__exit__rrcK|jSrArrs rr8znullcontext.__aenter__s  rc KdSrArr s rr:znullcontext.__aexit__s  rrA) r.r/r0r1rWrr%r8r:rrrr r sn))))!!!   !!!     rr c$eZdZdZdZdZdZdS)rzHNon thread-safe context manager to change the current working directory.c"||_g|_dSrA)path_old_cwd)rrs rrWzchdir.__init__s  rc|jtjtj|jdSrA)rrosgetcwdrrrs rrzchdir.__enter__s6 RY[[))) rc\tj|jdSrA)rrrrr s rr%zchdir.__exit__s& ""$$%%%%%rNrrrrrrsGRR&&&&&rr)#r1r4rrr' collectionsr functoolsrtypesrr__all__ABCr r objectrrLrQr[rmr rr rrrrrrrrr rrrrrs:: ********   SW,#'.v.     F    ????????0AFAFAFAFAF AFAFAFF>G>G>G>G>G >G>G>GBBB$2"""""*"""4<<<<<,<<<$     o    o MMMMM%MMM