duckdb / duckdb/duckdb

[Feature Request] Context Managers in Python API

Open
#3,152 7 comments 26 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
41.2k
Forks
3.8k
Avg merge
2d 9h
Merged PRs (30d)
496

Description

I was wondering whether you'd be open to modifying / adding to the Python API to use [context managers](https://docs.python.org/3/library/stdtypes.html#typecontextmanager) for more resource management. These would allow us to replace the following:

```python
# Old way
conn.register("name", obj)
try:
... # Use obj
finally:
conn.unregister("name")

# hypothetical API
with conn.register("name", obj):
...
```

which makes it less likely to leak memory by forgetting to unregister the connection. Another example might be to create something for a transaction:

```python
# Old Way
conn.begin()
try:
... # Execute transaction
except:
conn.rollback()
else:
conn.commit()

# Hypothetical API:
with conn.transaction(): # COMMITS on success, ROLLBACK on error
...
```

Implementing this would be a matter of returning special objects that implement `__enter__`and `__exit__` functions. I'd be happy to contribute the patch, but would want some guidance on naming (I'm particularly interested in the `register` case, since I'm not personally using transactions to insert data right now, but modifying `register` to return a special context manager would be a breaking change so we'd probably want a different name).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.