def _tmp_session(self, session, close=True):
        """If provided session is None, lend a temporary session."""
        if session:
            # Don't call end_session.
            yield session
            return

        s = self._ensure_session(session)
        if s and close:
            with s:
                # Call end_session when we exit this scope.
                yield s
        elif s:
            try:
                # Only call end_session on error.
                yield s
            except Exception:
                s.end_session()
                raise
        else:
            yield None
If provided session is None, lend a temporary session.
stackoverflow/venv/lib/python3.6/site-packages/pymongo/mongo_client.py