<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def detach(self, result, sync=True):
 """ Detach a result from this session by fetching and buffering any remaining records. :param result: :param sync: :returns: number of records fetched """

        count = 0

        if sync and result.attached():
            self.send()
            fetch = self.fetch
            while result.attached():
                count += fetch()

        if self._last_result is result:
            self._last_result = None
            if not self.has_transaction():
                self._disconnect(sync=False)

        result._session = None
        return count