code: def _get_or_create_legend(plot):
      # Using the simpler plot.select(type=Legend) to find the existing legend
      # here is very inefficient on already populated plots, therefore we do it
      # like this. TODO: This will need to be reworked when introducing nested
      # layouts!
      panels = (
          plot.above + plot.below + plot.left + plot.right + plot.center
      )
      legends = [obj for obj in panels if isinstance(obj, Legend)]
  
      if not legends:
          legend = Legend()
          plot.add_layout(legend)
          return legend
      if len(legends) == 1:
          return legends[0]
      raise RuntimeError(
          "Plot %s configured with more than one legend renderer, cannot use legend_* convenience arguments"
          % plot
      )
  
file_path: bokeh/src/bokeh/plotting/_legends.py
imports: from __future__ import annotations
  import logging
  import numpy
  from ..core.properties import field, value
  from ..models import Legend, LegendItem
  from ..util.strings import nice_join
label_desc: Use image node_id 4 for calling a global function with example usage: _get_or_create_legend(plot) and returns: legend, legends