MicroStrategy/mstrio-py

Connection as a contextmanager

Closed this issue · 2 comments

Is it planned to have a contextmanager handling the connection ?
This would ensure connections are closed and don't remain open.

Also this can be easily defined by the user, it'll surely helps if it's coded in the package.
Best would be to modify the Connection class but I guess it's too late now to change its behavior.

example:

from mstrio.connection import Connection
from contextlib import contextmanager

@contextmanager
def connect():
    connection = Connection(*args, **kwds)
    try:
        yield connection
    finally:
        connection.close()

# Automatically closes connection when done
with connect() as conn:
    ...
mstrpr commented

Hi @ismailmuller,
the Connection object already implements context manager protocol, so this:

with Connetion(...) as conn:
    ...

already works.

Thanks for the quick response.
I've not seen that in the docs but that's fine now.