def get_best_k(trials,
               k=1,
               status_whitelist=None,
               optimization_goal='minimize'):
  """Returns the top k trials sorted by objective_value.

  Args:
    trials: The trials (Trail objects) to sort and return the top_k of.
    k: The top k trials to return. If k=1 we don't return a list.
    status_whitelist: list of statuses to whitelist. If None, we use all trials.
    optimization_goal: string, minimize or maximize.

  Returns:
    The top k trials (list unless k=1) sorted by objective_value.
  """
  trials_ = trials
  valid_status = status_whitelist
  if valid_status is not None:
    trials_ = [
        trial for trial in trials_
        if trial.status in valid_status and not trial.trial_infeasible
    ]
  if not trials_:
    return None

  maximizing = optimization_goal != 'minimize'
  top = sorted(
      trials_,
      key=lambda t: t.final_measurement.objective_value,
      reverse=maximizing)
  return top[:k] if k > 1 else top[0]