Skip to content

[BUG] Bare connections cannot be used as context managers #583

Open
@sm-Fifteen

Description

@sm-Fifteen
  • asyncpg version: 0.20.1
  • PostgreSQL version: 10.3
  • Python version: 3.8.2
  • Platform: Windows
  • Do you use pgbouncer?: No
  • Did you install asyncpg with pip?: Yes

While under most use cases, people will want to use connection pools to manage their connections, there are times where using bare connections turns out to be more practical. However, while connection pools can be opened and closed via context managers:

async with asyncpg.create_pool(user='postgres', command_timeout=60) as pool:
    async with pool.acquire() as con:
        await con.fetch('SELECT 1')

...it appears that bare connections created via asyncpg.connect do not support this:

async with asyncpg.connect(user='postgres') as con:
    await con.fetch('SELECT 1')
File "./test.py", line 120, in fetch_ip_list
    async with asyncpg.connect(user="postgres") as con:
AttributeError: __aexit__

I personally like using with blocks to handle the scope of resources like this, so this is a step down for me in terms of ergonomics, not to mention rather surprising given that connections coming from connection pools do work as context managers (even though those are merely returned to the pool instead of closed).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions