# Implicitly close \`sqlite3\` connections with context managers

**URL:** <https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320>\
**Category:** Ideas\
**Tags:** sqlite3\
**Created:** [September 8, 2023, 3:57pm UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320 "2023-09-08T15:57:45Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![d33bs](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/d33bs/32/14556_2.png) [@d33bs](https://discuss.python.org/u/d33bs)\
**Post date:** [September 8, 2023, 3:57pm UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/1 "2023-09-08T15:57:45Z")

</div>

I’ve noticed a handful of scenarios where `sqlite3` connections remain open when using a context manager in Python. This sometimes happens when a developer forgets to implement an explicit `sqlite3.connect.close()` after / outside of the context manager’s closure.

This follows the [functionality found in the documentation](https://docs.python.org/3/library/sqlite3.html#sqlite3-connection-context-manager) (where connections must be explicitly closed, as per the statement `"Note The context manager neither implicitly opens a new transaction nor closes the connection."`. While it does follow the documentation, it might be less obvious when using context managers across different objects that do involve an implicit close. Would it make sense to enable an implicit connection close when using `sqlite3.connect()`'s in context managers to decrease the chance of surprising behavior and developer challenges?

For example, and somewhat related given the pattern of file-based object handling, the input and output documentation covering reading and writing files offers a familiar example that uses implicit file object closes with context managers.

Modified from [reading and writing files](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files):

```python
with open('workfile', encoding="utf-8") as f:
    read_data = f.read()

# the file object f is closed automatically

```

I propose that we follow a similar pattern with `sqlite3` connections, closing the connection with the context (instead of requiring an additional call outside of the context.

Modified from `sqlite3` docs linked above:

```python
with sqlite3.connect("workfile.sqlite") as con:
    con.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
    con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))

# proposed: the sqlite3 connection object con is closed automatically.
# as-is: an additional statement to con.close() is required to properly close the database connection.

```

Thank you in advance for reading and interested to hear your thoughts on this! I’d also be interested in the historical reasons for this, recognizing there’s likely a cause for the existing functionality.

---

<div class="post-metadata">

**Author:** ![barry-scott](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@barry-scott](https://discuss.python.org/u/barry-scott)\
**Post date:** [September 9, 2023, 9:10am UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/2 "2023-09-09T09:10:06Z")

</div>

The existing code has the context management handle the commit vs rollback case as the docs you link to show.

It is common that each connection is used more then once so that multiple transactions can be executed. In these cases closing the connection is not wanted.

The comparison with open() falls down when you considered multiple transactions.

---

<div class="post-metadata">

**Author:** ![erlendaasland](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/erlendaasland/32/4378_2.png) [@erlendaasland](https://discuss.python.org/u/erlendaasland)\
**Post date:** [September 9, 2023, 9:20am UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/3 "2023-09-09T09:20:13Z")

</div>

> [@barry-scott](#):
>
> It is common that each connection is used more then once so that multiple transactions can be executed. In these cases closing the connection is not wanted.

True; the proposed change would be a major breaking change for `sqlite3`.

> [@d33bs](#):
>
> I propose that we follow a similar pattern with `sqlite3` connections, closing the connection with the context (instead of requiring an additional call outside of the context.

I’m -1 to this. If the docs are unclear, we should instead try to improve them. For the behaviour you are looking for, I suggest using [contextlib.closing](https://docs.python.org/3/library/contextlib.html#contextlib.closing):

```python
import sqlite3
from contextlib import closing

with closing(sqlite3.connect(db)) as cx:
    with cx:
        do_complex_transaction(cx)
    with cx:
        do_another_complex_transaction(cx)

```

---

<div class="post-metadata">

**Author:** ![d33bs](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/d33bs/32/14556_2.png) [@d33bs](https://discuss.python.org/u/d33bs)\
**Post date:** [September 10, 2023, 2:14am UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/4 "2023-09-10T02:14:53Z")

</div>

Thanks @barry-scott - great point. To help account for forward compatibility of this feature without breaking prior behavior, maybe a parameter could be used, for example:

```python
with sqlite3.connect("workfile.sqlite", full_close_context=True) as con:
    con.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
    con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))

# proposed: the sqlite3 connection object con is closed automatically.
# as-is: an additional statement to con.close() is required to properly close the database connection.

```

---

<div class="post-metadata">

**Author:** ![d33bs](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/d33bs/32/14556_2.png) [@d33bs](https://discuss.python.org/u/d33bs)\
**Post date:** [September 10, 2023, 2:24am UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/5 "2023-09-10T02:24:06Z")

</div>

Thank you @erlendaasland - I wasn’t familiar with `contextlib.close` and thought the solution you raised was very elegant. I tried a modified version of what you provided mixing in what I posted earlier and it worked as described (see below).

```python
import sqlite3
from contextlib import closing

with closing(sqlite3.connect("workfile.sqlite")) as cx:
    with cx:
        cx.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
        cx.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))

# no need to close the connection as contextlib.closing closed it for us

```

To your point about improving the docs, I’d love to see `contextlib.closing` mentioned somewhere on the sqlite3 docs to help describe the multi-transactional case of how `sqlite3.connect()` contexts function by default along with a workaround for cases where folks would like to use it for singular transactions.

---

<div class="post-metadata">

**Author:** ![jamestwebber](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jamestwebber/32/12799_2.png) [@jamestwebber](https://discuss.python.org/u/jamestwebber)\
**Post date:** [September 10, 2023, 2:31am UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/6 "2023-09-10T02:31:45Z")

</div>

> [@d33bs](#):
>
> To your point about improving the docs, I’d love to see `contextlib.closing` mentioned somewhere on the sqlite3 docs to help describe the multi-transactional case of how `sqlite3.connect()` contexts function by default along with a workaround for cases where folks would like to use it for singular transactions.

I agree with this. I had no idea `contextlib.closing` existed until this thread, and it’s perfect for this use. No need to modify `connect` at all.

---

<div class="post-metadata">

**Author:** ![Stefan2](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/stefan2/32/18492_2.png) [@Stefan2](https://discuss.python.org/u/Stefan2)\
**Post date:** [September 10, 2023, 8:04am UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/7 "2023-09-10T08:04:33Z")

</div>

I don’t think you need to nest it, can do this:

```python
import sqlite3
from contextlib import closing

with closing(sqlite3.connect("workfile.sqlite")) as cx, cx
    cx.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
    cx.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))

# no need to close the connection as contextlib.closing closed it for us

```

Demo:

```python
from contextlib import closing, contextmanager

class connect:
    def execute(self, command):
        print(command)
    def close(self):
        print('close')
    def __enter__ (self):
        print('enter')
    def __exit__ (self, exc_type, exc_val, exc_tb):
        print('exit')

with closing(connect()) as cx, cx:
    cx.execute('query')

```

Output ([Attempt This Online!](https://ato.pxeger.com/run?1=dVBLDoIwEI1bTtFdIUHXxoO4bUoZoElpsQxazuKGjR7K01go1Rh1Vs37TOe9670bsTF6mm4DVtv9Y3OsrGmJMBrBoZIFkW1nLBKhTC91nUeq5ZrXYJNEKN73M6pB4CEhfkqoCDgQA0Lag6pmU-sNZRb4eTorNaYRf9nmb4LpS0sXjr61jIE_xTL2R7-wn3oncZXn_kLBcOwgvM5crVDxY5P3-UXJRWITm0jXyGmWEe4LcD6lC07hdjE-PQ1gR5qFeteWY9tP)):

```none
enter
query
exit
close

```

---

<div class="post-metadata">

**Author:** ![erlendaasland](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/erlendaasland/32/4378_2.png) [@erlendaasland](https://discuss.python.org/u/erlendaasland)\
**Post date:** [September 10, 2023, 2:24pm UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/8 "2023-09-10T14:24:40Z")

</div>

> [@Stefan2](#):
>
> I don’t think you need to nest it,

True, you don’t _need_ to nest it if you’ve only got one transaction. But, I prefer the explicit variant. It is more readable, IMO.

---

<div class="post-metadata">

**Author:** ![erlendaasland](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/erlendaasland/32/4378_2.png) [@erlendaasland](https://discuss.python.org/u/erlendaasland)\
**Post date:** [September 10, 2023, 2:26pm UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/9 "2023-09-10T14:26:41Z")

</div>

> [@d33bs](#):
>
> To your point about improving the docs, I’d love to see `contextlib.closing` mentioned somewhere on the sqlite3 docs to help describe the multi-transactional case of how `sqlite3.connect()` contexts function by default along with a workaround for cases where folks would like to use it for singular transactions.

I’ll create an issue for this. (Feel free to beat me to it 🙂)

---

<div class="post-metadata">

**Author:** ![d33bs](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/d33bs/32/14556_2.png) [@d33bs](https://discuss.python.org/u/d33bs)\
**Post date:** [September 10, 2023, 6:36pm UTC](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320/10 "2023-09-10T18:36:12Z")

</div>

> [@erlendaasland](#):
>
> Feel free to beat me to it 🙂

Thanks @erlendaasland ! I hope you don’t mind, I went ahead and created an issue 🙂 :

> <https://github.com/python/cpython/issues/109234>
>
> This issue covers an opportunity to enhance the existing \[\`sqlite3\` docs on cont…ext management\](https://docs.python.org/3/library/sqlite3.html#sqlite3-connection-context-manager) by adding a mention of \[\`contextlib.closing\`\](https://docs.python.org/3/library/contextlib.html#contextlib.closing) to help guide developers when performing singular transactions. Adding this section to the documentation would help guide developers in use cases where they'd like to close the \`sqlite3\` connection without an additional \`sqlite.connect().close()\` after a context manager closes.
> 
> For default \`sqlite3\` context management cases which don't use \`contextlib.closing\` we could outline or strengthen existing mention that the intention is to perform multiple transactions without fully closing the connection. This might help distinguish development options / decision-making for Python developers reading through the documentation.
> 
> A \`contextlib.closing\` example we could include:
> 
> \`\`\`python
> import sqlite3
> from contextlib import closing
> 
> with closing(sqlite3.connect("workfile.sqlite")) as cx:
> with cx:
> cx.execute("CREATE TABLE lang(id INTEGER PRIMARY KEY, name VARCHAR UNIQUE)")
> cx.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))
> 
> \# no need to close the connection as contextlib.closing closed it for us
> \`\`\` 
> 
> Related to \[a discussion from discuss.python.org\](https://discuss.python.org/t/implicitly-close-sqlite3-connections-with-context-managers/33320). Many thanks to @erlend-aasland for suggesting the \`contextlib.closing\` approach and the others in the discussion thread for their help in discussing this topic.
> 
> 
> \### Linked PRs
> \* gh-109322
> \* gh-110293
> \* gh-110294
