MicroStrategy / mstrio-py

Python integration for MicroStrategy
Apache License 2.0
90 stars 59 forks source link

Connection as a contextmanager #158

Closed ismailmuller closed 1 year ago

ismailmuller commented 1 year ago

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 1 year ago

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

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

already works.

ismailmuller commented 1 year ago

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