Do not use an empty list as a default argument
Clean codePython
Using an empty list as default argument might lead to unwanted consequences down the line.
In fact, according to Python's documentation, default arguments are evaluated once when the function is defined, not each time the function is called. This means that if you use a mutable default argument like the aforementionned empty list and mutate it, you will and have mutated that object for all future calls to the function as well.
Examples
Example 1:
Positive
Correct implementation following the practice.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
class Classroom:
def __init__(self, level, students=None):
self.level = level
if students is None:
self.students = []
else:
self.students = students
@property
def nb_students(self) -> int:
return len(self.students)
@property
def avg_age(self) -> float:
return sum(student.age for student in self.students) / self.nb_students
Negative
Incorrect implementation that violates the practice.
from dataclasses import dataclass
@dataclass
class Student:
name: str
age: int
class Classroom:
def __init__(self, level, students=[]):
self.level = level
self.students = students
@property
def nb_students(self) -> int:
return len(self.students)
@property
def avg_age(self) -> float:
return sum(student.age for student in self.students) / self.nb_students