<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def open_if_needed(self, mode=None):
 """ Convenience context-manager for the use with ``with``. Opens the container if not already done. Only closes the container if it was opened within this context. Args: mode (str):
 Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``. """

        was_open = self.is_open()

        if not was_open:
            self.open(mode=mode)

        try:
            yield self
        finally:
            if not was_open:
                self.close()