Python Forum
Dealing with multiple context managers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dealing with multiple context managers
#6
(Nov-15-2018, 04:57 PM)heras Wrote: Maybe I can also use asynccontextmanager to get the structure I want.

I guess you can do this. Using await in the context, requires to be inside a async function.

EDIT:

You can't mix synchronous and asynchronous context managers :-(
You can stack them only.
Calling a blocking synchronous function in async code, will block the whole event-loop.

What works:
In [35]: @contextlib.asynccontextmanager 
    ...: async def async_ctx(): 
    ...:     print('Entering async context') 
    ...:     await asyncio.sleep(5) 
    ...:     yield 
    ...:     print('Leaving async context') 
    ...:                                                                        

In [36]: @contextlib.contextmanager 
    ...: def sync_ctx(): 
    ...:     print('Entering sync context') 
    ...:     yield 42 
    ...:     print('Leaving sync context')                                      

In [37]: async def run(): 
    ...:     async with async_ctx(): 
    ...:         with sync_ctx() as sync_ret: 
    ...:             print(sync_ret)                                            

In [38]: asyncio.run(run())                                                     
Entering async context
Entering sync context
42
Leaving sync context
Leaving async context
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Dealing with multiple context managers - by heras - Nov-14-2018, 10:07 PM
RE: Dealing with multiple context managers - by DeaD_EyE - Nov-16-2018, 09:01 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel from SAP - dealing with formats and VBA MasterOfDestr 7 592 Feb-25-2024, 12:23 PM
Last Post: Pedroski55
  Context-sensitive delimiter ZZTurn 9 1,517 May-16-2023, 07:31 AM
Last Post: Gribouillis
  How does open context manager work? deanhystad 7 1,354 Nov-08-2022, 02:45 PM
Last Post: deanhystad
  UnicodeEncodeError - Dealing with Japanese Characters fioranosnake 2 2,495 Jul-07-2022, 08:43 PM
Last Post: fioranosnake
  Decimal context stevendaprano 1 1,048 Apr-11-2022, 09:44 PM
Last Post: deanhystad
  Dealing with duplicated data in a CSV file bts001 10 11,584 Sep-06-2021, 12:11 AM
Last Post: SamHobbs
  TextIOWrapper.tell() with Python 3.6.9 in context of 0D/0A fschaef 0 2,086 Mar-29-2020, 09:18 AM
Last Post: fschaef
  Dealing with a .json nightmare... ideas? t4keheart 10 4,420 Jan-28-2020, 10:12 PM
Last Post: t4keheart
  Dealing with Exponential data parthi1705 11 9,821 May-30-2019, 10:16 AM
Last Post: buran
  Smtplib: What does context argument means? Pythenx 1 3,096 Mar-27-2019, 06:25 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020