code: def _build_discrete_cmap(cmap, levels, extend, filled):
      
      import matplotlib as mpl
  
      if not filled:
          # non-filled contour plots
          extend = 'max'
  
      if extend == 'both':
          ext_n = 2
      elif extend in ['min', 'max']:
          ext_n = 1
      else:
          ext_n = 0
  
      n_colors = len(levels) + ext_n - 1
      pal = _color_palette(cmap, n_colors)
  
      new_cmap, cnorm = mpl.colors.from_levels_and_colors(
          levels, pal, extend=extend)
      # copy the old cmap name, for easier testing
      new_cmap.name = getattr(cmap, 'name', cmap)
  
      return new_cmap, cnorm
docs: Build a discrete colormap and normalization of the data.