ComeçarComece gratuitamente

Práticas recomendadas para argumentos padrão

Um de seus colegas de trabalho (que obviamente não fez este curso) escreveu esta função para adicionar uma coluna a um DataFrame do pandas. Infelizmente, eles usaram uma variável mutável como um valor de argumento padrão! Mostre a eles uma maneira melhor de fazer isso para que não tenham um comportamento inesperado.

def add_column(values, df=pandas.DataFrame()):

  """Add a column of `values` to a DataFrame `df`.

  The column will be named "col_<n>" where "n" is

  the numerical index of the column.


  Args:

    values (iterable): The values of the new column

    df (DataFrame, optional): The DataFrame to update.

      If no DataFrame is passed, one is created by default.


  Returns:

    DataFrame

  """

  df['col_{}'.format(len(df.columns))] = values

  return df

Este exercício faz parte do curso

Como escrever funções em Python

Ver Curso

Instruções de exercício

  • Altere o valor padrão de df para um valor imutável para seguir as práticas recomendadas.
  • Atualize o código da função para que um novo DataFrame seja criado se o chamador não tiver passado um.

Exercício interativo prático

Experimente este exercício preenchendo este código de exemplo.

# Use an immutable variable for the default argument
def better_add_column(values, df=____):
  """Add a column of `values` to a DataFrame `df`.
  The column will be named "col_" where "n" is
  the numerical index of the column.

  Args:
    values (iterable): The values of the new column
    df (DataFrame, optional): The DataFrame to update.
      If no DataFrame is passed, one is created by default.

  Returns:
    DataFrame
  """
  # Update the function to create a default DataFrame
  if ____ is ____:
    df = pandas.DataFrame()
  df['col_{}'.format(len(df.columns))] = values
  return df
Editar e executar código