Skip to content

Commit be15003

Browse files
refactor: fix dangerous default argument
Do not use a mutable like `list` or `dictionary` as a default value to an argument. Python’s default arguments are evaluated once when the function is defined. Using a mutable default argument and mutating it will mutate that object for all future calls to the function as well.
1 parent 0116ca7 commit be15003

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

demo_code.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,17 @@ class RandomNumberGenerator:
4646
def limits(self):
4747
return self.limits
4848

49-
def get_number(self, min_max=[1, 10]):
49+
def get_number(self, min_max=None):
5050
"""Get a random number between min and max."""
51+
if min_max is None:
52+
min_max = [1, 10]
5153
assert all([isinstance(i, int) for i in min_max])
5254
return random.randint(*min_max)
5355

5456

55-
def main(options: dict = {}) -> str:
57+
def main(options: dict = None) -> str:
58+
if options is None:
59+
options = {}
5660
pdb.set_trace()
5761
if "run" in options:
5862
value = options["run"]
@@ -71,7 +75,9 @@ def main(options: dict = {}) -> str:
7175
f.close()
7276

7377

74-
def moon_chooser(moon, moons=["europa", "callisto", "phobos"]):
78+
def moon_chooser(moon, moons=None):
79+
if moons is None:
80+
moons = ["europa", "callisto", "phobos"]
7581
if moon is not None:
7682
moons.append(moon)
7783

0 commit comments

Comments
 (0)