Dobre praktyki dotyczące domyślnych argumentów
Twój współpracownik (który najwyraźniej nie przeszedł tego kursu) napisał funkcję dodającą kolumnę do DataFrame'a z biblioteki pandas. Niestety użył mutowalnej zmiennej jako domyślnej wartości argumentu! Pokaż mu lepsze rozwiązanie, żeby uniknąć niespodziewanego zachowania programu.
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
To ćwiczenie jest częścią kursu
Pisanie funkcji w Pythonie
Instrukcje do ćwiczenia
- Zmień domyślną wartość
dfna niemutowalną, zgodnie z dobrymi praktykami. - Zaktualizuj kod funkcji tak, aby nowy DataFrame był tworzony wtedy, gdy wywołujący nie przekaże żadnego.
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
# 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