Лучшие практики для аргументов по умолчанию
Ваш коллега (который, очевидно, не проходил этот курс) написал функцию для добавления столбца в DataFrame из библиотеки pandas. К сожалению, он использовал изменяемую переменную в качестве значения аргумента по умолчанию! Покажите ему, как сделать это правильно, чтобы избежать неожиданного поведения программы.
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 создавался в том случае, если вызывающий код не передал его явно.
Интерактивное практическое упражнение
Попробуйте выполнить это упражнение, дополнив этот пример кода.
# 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