def pop_messages(self, type=None):
        """Retrieve stored messages and remove them from the session.

        Return all messages with a specific type, or all messages when `type`
        is None. Messages are returned in the order they were added. All
        messages returned in this way are removed from the session and will not
        be returned in subsequent calls.

        Returns a list of namedtuples with the fields (type, text).
        """
        key = self._msg_key
        messages = []
        if type is None:
            messages = self.pop(key, [])
        else:
            keep_messages = []
            for msg in self.get(key, []):
                if msg.type == type:
                    messages.append(msg)
                else:
                    keep_messages.append(msg)
            if not keep_messages and key in self:
                del self[key]
            else:
                self[key] = keep_messages
        if messages:
            self.save()

        return messages