From 08af4ce9bd3046b14af407f7b7c603dbd888d6ee Mon Sep 17 00:00:00 2001 From: andygoblins Date: Sat, 22 Feb 2020 11:28:50 -0600 Subject: [PATCH] context manager examples --- .../python/example_scripts/simple_book.py | 16 +++++++------- .../python/example_scripts/simple_session.py | 21 +++++++------------ 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/bindings/python/example_scripts/simple_book.py b/bindings/python/example_scripts/simple_book.py index 9a6040b928..19ebb01865 100644 --- a/bindings/python/example_scripts/simple_book.py +++ b/bindings/python/example_scripts/simple_book.py @@ -11,15 +11,15 @@ from gnucash import Session uri = "xml:///tmp/simple_book.gnucash" print("uri:", uri) -ses = Session(uri, is_new=True) -book = ses.get_book() +with Session(uri, is_new=True) as ses: + book = ses.get_book() -#Call some methods that produce output to show that Book works -book.get_root_account().SetDescription("hello, book") -print("Book is saved:", not book.session_not_saved()) + #Call some methods that produce output to show that Book works + book.get_root_account().SetDescription("hello, book") + print("Book is saved:", not book.session_not_saved()) -print("saving...") -ses.save() + #As long as there's no exceptions, book is automatically saved + #when session ends. + print("saving...") print("Book is saved:", not book.session_not_saved()) -ses.end() diff --git a/bindings/python/example_scripts/simple_session.py b/bindings/python/example_scripts/simple_session.py index 3bd219c9c9..05da9487ba 100644 --- a/bindings/python/example_scripts/simple_session.py +++ b/bindings/python/example_scripts/simple_session.py @@ -19,18 +19,13 @@ except GnuCashBackendException as backend_exception: # create a new file, this requires a file type specification -session = Session("xml://%s" % FILE_2, is_new=True) -session.save() -session.end() -session.destroy() +with Session("xml://%s" % FILE_2, is_new=True) as session: + book = session.book + root = book.get_root_account() # open the new file, try to open it a second time, detect the lock -session = Session(FILE_2) -try: - session_2 = Session(FILE_2) -except GnuCashBackendException as backend_exception: - assert( ERR_BACKEND_LOCKED in backend_exception.errors ) -session.end() -session.destroy() - - +with Session(FILE_2) as session: + try: + session_2 = Session(FILE_2) + except GnuCashBackendException as backend_exception: + assert( ERR_BACKEND_LOCKED in backend_exception.errors )