Skip to content

fix: support async with on async persister factory methods#681

Open
andreahlert wants to merge 1 commit intoapache:mainfrom
andreahlert:fix/issue-546-async-context-manager
Open

fix: support async with on async persister factory methods#681
andreahlert wants to merge 1 commit intoapache:mainfrom
andreahlert:fix/issue-546-async-context-manager

Conversation

@andreahlert
Copy link
Contributor

Summary

Fixes #546

AsyncSQLitePersister.from_values() and AsyncPostgreSQLPersister.from_values() are async classmethods that return coroutines. Using them directly with async with fails with:

TypeError: 'coroutine' object does not support the asynchronous context manager protocol

This PR introduces _AsyncPersisterContextManager, a thin wrapper that implements both __await__ and __aenter__/__aexit__, so factory methods now support both usage patterns:

# await (backwards compatible)
persister = await AsyncSQLitePersister.from_values(db_path="test.db")

# async with (what the issue requested)
async with AsyncSQLitePersister.from_values(db_path="test.db") as persister:
    await persister.initialize()
    ...

The same fix is applied to AsyncPostgreSQLPersister in b_asyncpg.py.

Test plan

  • Reproduced the original TypeError in a Docker container (Python 3.11)
  • Verified async with ... from_values() works after the fix
  • Verified await ... from_values() still works (backwards compatibility)
  • @skrawcz review
  • @kajocina validate against original use case

`AsyncSQLitePersister.from_values()` and `AsyncPostgreSQLPersister.from_values()`
were async classmethods returning coroutines, which cannot be used directly
with `async with`. This wraps them in `_AsyncPersisterContextManager` that
supports both `await` (backwards compatible) and `async with` protocols.

Closes apache#546
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Async state persister doesn't work as a context manager

1 participant