始める無料で始める

デフォルト引数のベストプラクティス

同僚(このコースを受けていないのは明らかですね)が、pandas の DataFrame に列を追加する関数を書きました。ところが、デフォルト引数にミュータブルな変数を使ってしまっています!予期せぬ動作を避けられるように、より良い書き方を教えてあげましょう。

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

この演習はコースの一部です

Python関数の書き方

コースを見る

演習の手順

  • ベストプラクティスに従い、df のデフォルト値をイミュータブルな値に変更してください。
  • 呼び出し側が DataFrame を渡さなかった場合は新しい DataFrame を作成するよう、関数のコードを更新してください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# 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
コードを編集して実行