Tinche / aiofiles

File support for asyncio
Apache License 2.0
2.62k stars 151 forks source link

Use of open without a context manager? #139

Open allComputableThings opened 2 years ago

allComputableThings commented 2 years ago

While I love context managers, the stack isn't always the the place to perform clean up. open can be used without async with. How can I use aiofiles.open without it?

import asyncio

import aiofiles

async def test():
    f = aiofiles.open('filename.txt', mode='w')
    try:
        #await f.write('123') #  'AiofilesContextManager' object has no attribute 'write'
        await f.send('123') # TypeError: can't send non-None value to a just-started generator
    finally:
        f.close()
asyncio.run(test())
DivineSentry commented 2 years ago

seconded. im currently writing code which would benefit from opening aiofiles without a context manager.

shan-guo commented 2 years ago

这是来自QQ邮箱的假期自动回复邮件。您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。

byehack commented 1 year ago

for temporary workaround you can call __aenter__ directly:

import asyncio

import aiofiles

async def test():
    f = await aiofiles.open('filename.txt', mode='w').__aenter__()
    try:
        await f.write('123') #  Now works
    finally:
        f.close()
asyncio.run(test())