code: def _patch_loop(loop):
      """
      This function is designed to work around https://bugs.python.org/issue36607
  
      It's job is to keep a thread safe variable tasks up to date with any tasks that
      are created for the given loop. This then lets you cancel them as _all_tasks
      was intended for.
  
      We also need to patch the {get,set}_task_factory functions because we can't allow
      Other users of it to overwrite our factory function. This function will pretend
      like there is no factory set but in reality our factory is always set and we will
      call the provided one set
      """
      tasks = weakref.WeakSet()
  
      task_factory = [None]
  
      def _set_task_factory(factory):
          task_factory[0] = factory
  
      def _get_task_factory():
          return task_factory[0]
  
      def _safe_task_factory(loop, coro):
          if task_factory[0] is None:
              # These lines are copied from the standard library because they don't have
              # this inside a default factory function for me to call.
              # https://github.com/python/cpython/blob/3.6/Lib/asyncio/base_events.py#L304
              task = asyncio.Task(coro, loop=loop)
              if task._source_traceback:
                  del task._source_traceback[-1]  # pragma: no cover
          else:
              task = task_factory[0](loop, coro)
          tasks.add(task)
          return task
  
      loop.set_task_factory(_safe_task_factory)
      loop.set_task_factory = _set_task_factory
      loop.get_task_factory = _get_task_factory
  
      return tasks
  
imports: import asyncio
  import weakref
  from typing import Any, Awaitable, Coroutine, TypeVar, Union
label_desc: Use image node_id 1 for calling a global function with example usage: _patch_loop(loop) and returns: tasks, task_factory, task