Vc.ics|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.self #/usr/lib64/python3.11/contextlib.py __enter__z AbstractContextManager.__enter__s csdSz9Raise any exception triggered within the runtime context.Nrrexc_typeZ exc_value traceback r__exit__zAbstractContextManager.__exit__s trcN|turtj|ddStS)Nrr#)r _collections_abc_check_methodsNotImplementedclsZC r__subclasshook__z'AbstractContextManager.__subclasshook__ s, ( ( O#21k:NN NrN) __name__ __module__ __qualname____doc__ classmethodr__class_getitem__rabcabstractmethodr#r+rrrr r ss66# L11 [rr cr)r z9An abstract base class for asynchronous context managers.c K|Srrrrr __aenter__z&AbstractAsyncContextManager.__aenter__-s  rcs KdSrrrr"r __aexit__z%AbstractAsyncContextManager.__aexit__1s trcr$)Nr5r6)r r%r&r'r(r*rr+z,AbstractAsyncContextManager.__subclasshook__6s6 - - @#21l3>@@ @rN) r,r-r.r/r0rr1r5r2r3r6r+rrrr r 'ssCC# L11 [rr ceZdZdZdZdZdS)r zJA base class or mixin that enables context managers to work as decorators.cr)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. rrrr _recreate_cmzContextDecorator._recreate_cmAs  rc@tfd}|S)Ncsp5|i|cdddS#1swxYwYdSNr8argskwdsfuncr rinnerz(ContextDecorator.__call__..innerNs""$$ + +tT*T** + + + + + + + + + + + + + + + + + +s +//rrr?rA`` r__call__zContextDecorator.__call__Ms9 t + + + + +  + rNr,r-r.r/r8rDrrrr r >s8PP   rr cr7)AsyncContextDecoratorzPA base class or mixin that enables async context managers to work as decorators.cr)z-Return a recreated instance of self. rrrrr8z"AsyncContextDecorator._recreate_cmXs  rcr9)NcsK4d{V|i|d{Vcdddd{VS#1d{VswxYwYdSr:r;r<r@rrAz-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 rrBrCrrDzAsyncContextDecorator.__call__]s9 t 1 1 1 1 1  1 rNrErrrrFrFUs8VV rrFcr7)_GeneratorContextManagerBasezBShared functionality for @contextmanager and @asynccontextmanager.cs||i||_|||c|_|_|_t |dd}|t |j}||_dS)Nr/)genr?r=r>getattrtyper/)rr?r=r>Zdoc r__init__z%_GeneratorContextManagerBase.__init__hs`4&&&*.d' 49didIt,,  %t**$C rcsN||j|j|jSr:)Z __class__r?r=r>rrrr8z)_GeneratorContextManagerBase._recreate_cmvs ~~diDI>>>rN)r,r-r.r/rLr8rrrrGrGes8LL?????rrGcr7)_GeneratorContextManagerz%Helper for @contextmanager decorator.cst|`|`|` t|jS#t $rt ddwxYwNzgenerator didn't yield)r=r>r?nextrH StopIteration RuntimeErrorrrrrz"_GeneratorContextManager.__enter__sU Ity$) C>> ! C C C788d B Cs7cs|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()) rOrHrQrPZthrowZ __traceback__ isinstance __cause__ BaseExceptionrZtypZvaluer!excrKrr#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-r.r/rr#rrrrMrM}sB 0/CCC1F1F1F1F1FrrMcr7)_AsyncGeneratorContextManagerz*Helper for @asynccontextmanager decorator.csK|`|`|` t|jd{VS#t $rt ddwxYwrN)r=r>r?anextrHStopAsyncIterationrQrrrr5z(_AsyncGeneratorContextManager.__aenter__sk Ity$) Ctx(((((( (! C C C788d B Cs$?csK|; 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)NrRFz$generator didn't stop after athrow()) rYrHrQrZZathrowrSrPrTrUrVrKrr6z'_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-r.r/r5r6rrrrXrXsB 54CCC.G.G.G.G.GrrXc<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||Sr:)rMr=r>r? rhelperzcontextmanager..helpers'dD999rrr?r_` rrrs36 4[[::::[: Mrcr[)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: cr\r:)rXr]r^rr_z#asynccontextmanager..helper=s,T4>>>rrr`rarrr"s36 4[[????[? Mrc$eZdZdZdZdZdZdS)ra2Context 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||_dSr:thingrrer*rrLzclosing.__init__T  rc|jSr:rdrrrrzclosing.__enter__Vs zrcs8|jdSr:)recloserexc_infor*rr#zclosing.__exit__Xs rNr,r-r.r/rLrr#rrrrrCsK rrcrb)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() crcr:rdrfr*rrLzaclosing.__init__nrgrcK|jSr:rdrrrr5zaclosing.__aenter__pszrcsHK|jd{VdSr:)reacloserjr*rr6zaclosing.__aexit__rs2j!!!!!!!!!!!rN)r,r-r.r/rLr5r6rrrrr\sK""""""rrcs$eZdZdZdZdZdZdS)_RedirectStreamNc"||_g|_dSr:) _new_target _old_targets)rZ new_targetr*rrLz_RedirectStream.__init__zs%rcs|jtt|jt t|j|j|jSr:)rrappendrIsys_streamsetattrrqrrrrz_RedirectStream.__enter__sE   dl!;!;<<<T\4#3444rcsjtt|j|jdSr:)rvrtrurrpoprZexctypeZexcinstZexctbr"rr#z_RedirectStream.__exit__s+T\4#4#8#8#:#:;;;;;r)r,r-r.rurLrr#rrrrorovsFG    <<<< r _exit_wrapperz8_BaseExitStack._create_cb_wrapper.._exit_wrappers Hd #d # # # # #rrrr=r>r``` r_create_cb_wrapperz!_BaseExitStack._create_cb_wrappers. $ $ $ $ $ $ $rcs,t|_dSr:)r_exit_callbacksrrrrLz_BaseExitStack.__init__s$wwrcsrt|}|j|_t|_|S)z@Preserve the context stack by transferring it to a new instance.)rJrr)rZ new_stackr*rpop_allz_BaseExitStack.pop_alls0DJJLL $($8 !$wwrcst|} |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). )rJr# _push_cm_exitAttributeError_push_exit_callbackrZexitZ_cb_typeZ exit_methodr"rpushz_BaseExitStack.pushsu:: 2"+K   t[ 1 1 1 1  + + +  $ $T * * * * * +  s/AAcst|} |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)rJrr#r TypeErrorr-r.rrrr)Z_enterZ_exitZresult r enter_contextz_BaseExitStack.enter_contexts2hh S]FLEE S S SHHH1AHHHIINR S S 2u%%% s  ,A cs`|j|g|Ri|}||_|||S)z\Registers an arbitrary callback and arguments. Cannot suppress exceptions. )r __wrapped__rrrr=r>rrKrrz_BaseExitStack.callbacksI 0/H4HHH4HH %- !   ///rc^|||}||ddS)z;Helper to correctly register callbacks to __exit__ methods.TN)rrrrrrr"rrz_BaseExitStack._push_cm_exits311"g>>    55555rTcs>|j||fdSr:)rrs)rris_syncs rrz"_BaseExitStack._push_exit_callback s$ ##Wh$788888rN)T)r,r-r.r/ staticmethodrrrLrrrrrrrrrr~r~s88''\'\ '''(&   666 999999rr~crb)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. crr:rrrrrzExitStack.__enter__s rcs |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|}||_dSr: __context__Znew_excZold_excZ exc_context frame_exc r_fix_exception_contextz2ExitStack.__exit__.._fix_exception_context%S &%1 +*@F)+% &#*G   rFTNNNrtrkrrwrrU) 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"B77Ccs4|ddddSz%Immediately unwind the context stack.N)r#rrrrizExitStack.closePs dD$'''''rN)r,r-r.r/rr#rirrrrrsL//////b(((((rrcsheZdZdZedZedZdZdZdZ dZ dZ d Z d Z d S) r aAsync 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. crr:rrr*r_create_async_exit_wrapperz)AsyncExitStack._create_async_exit_wrappercrrcr)Ncs(Kid{VdSr:rrrrrz>AsyncExitStack._create_async_cb_wrapper.._exit_wrapperis4(D)D)) ) ) ) ) ) ) ) ) )rrrrr_create_async_cb_wrapperz'AsyncExitStack._create_async_cb_wrappergs. * * * * * * *rcsKt|} |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)rJr5r6rrr-r._push_async_cm_exitrrrenter_async_contextz"AsyncExitStack.enter_async_contextms 2hh '^FMEE ' ' 'UUU1AUUU"& ' 'vbzz!!!!!!   U+++ s ",Acst|} |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)rJr6rrrrr"rpush_async_exitzAsyncExitStack.push_async_exitsw:: 8",K  $ $T; 7 7 7 7  2 2 2  $ $T5 1 1 1 1 1 2  s/ AAcsb|j|g|Ri|}||_||d|S)zfRegisters an arbitrary coroutine function and arguments. Cannot suppress exceptions. F)rrrrrKrpush_async_callbackz"AsyncExitStack.push_async_callbacksK 65hNNNNNN %- !   666rcsDK|dddd{VdSr)r6rrrrnzAsyncExitStack.acloses4nnT4...........rcr)zLHelper to correctly register coroutine function to __aexit__ method.FN)rrrr"rrz"AsyncExitStack._push_async_cm_exits577GDD    66666rcr4r:rrrrr5zAsyncExitStack.__aenter__s  rcs 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)Nrrcrr:rrrrrz8AsyncExitStack.__aexit__.._fix_exception_contextrrFTrr) rrrrrrrrZ cb_suppressrrrs @rr6zAsyncExitStack.__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-r.r/rrrrrrrnrr5r6rrrr r Vs  ''\'\ $$   ///777 3/3/3/3/3/rr cs2eZdZdZddZdZdZdZdZdS) 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 Ncrcr: enter_result)rrr*rrLznullcontext.__init__s(rcrhr:rrrrrznullcontext.__enter__s   rcr|r:rrZexcinfor*rr#znullcontext.__exit__r}rcrmr:rrrrr5znullcontext.__aenter__s  rcs KdSr:rrr*rr6znullcontext.__aexit__s  rr:) r,r-r.r/rLrr#r5r6rrrr r sn))))!!!   !!!     rr crb)rzHNon thread-safe context manager to change the current working directory.crpr:)path_old_cwd)rrr*rrLzchdir.__init__s  rcs|jtjtj|jdSr:)rrsosZgetcwdrrrrrrzchdir.__enter__s6 RY[[))) rcs\tj|jdSr:)rrrrwrr*rr#zchdir.__exit__s& ""$$%%%%%rNrlrrrrrsGRR&&&&&rr)#r/r2rrtr%Z collectionsrZ functoolsrZtypesrrZ__all__ZABCr r Zobjectr rFrGrMrXrrrrrorrrr~rr r rrrrrs:: ********   SW,#'.v.     F    ????????0AFAFAFAFAF AFAFAFF>G>G>G>G>G >G>G>GBBB$2"""""*"""4<<<<<,<<<$     o    o MMMMM%MMM