This is a part of a project I'm working on. The codebase is Python 2.7 and I don't have an option to switch to Python 3.
import shelve def get_document_info(): token_shelf = False try: token_shelf = shelve.open(os.path.join(current_dir, 'document_info.shelve')) token_mapping = token_shelf['token_mapping'] if token_mapping: return token_mapping else: return False except Exception, e: pass finally: if token_shelf: token_shelf.close()
Shelve is a persistent, dictionary-like object. More info can be found at https://docs.python.org/2/library/shelve.html
I need to ensure that
token_shelf is closed at the end. In the beginning of the function, what do I define
token_shelf as? If I don't define something there, PyCharm will throw an error saying that the
finally block does not exist.
What's the ideal way to write this piece of code? How can it be made more elegant and Pythonic?
PS: This code is working as expected right now.