Skip to content

Commit

Permalink
Add default arguments mistake
Browse files Browse the repository at this point in the history
  • Loading branch information
baniasbaabe committed Dec 30, 2023
1 parent ee8abe3 commit e5ed341
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions book/pythontricks/Chapter.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,56 @@
"p = Point(x=3.2, y=1.0)\n",
"print(p.x, p.y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mutable Default Values for Function Arguments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One big mistake in Python:\n",
"\n",
"Using mutable default values for function arguments.\n",
"\n",
"When using mutable objects like a list as a default value, you have to be careful.\n",
"\n",
"See the example below, where the default list is shared among all calls to the function.\n",
"\n",
"To fix this, set the default value to None and create a new list inside the function if no list is provided."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Dangerous behaviour:\n",
"def increment_numbers(numbers=[]):\n",
" for i in range(3):\n",
" numbers.append(i)\n",
" print(f\"Numbers: {numbers}\")\n",
"\n",
"increment_numbers() # Output: Numbers: [0, 1, 2]\n",
"increment_numbers() # Output: Numbers: [0, 1, 2, 0, 1, 2]\n",
"\n",
"\n",
"# Better:\n",
"def increment_numbers(numbers=None):\n",
" if numbers is None:\n",
" numbers = []\n",
" for i in range(3):\n",
" numbers.append(i)\n",
" print(f\"Numbers: {numbers}\")\n",
"\n",
"increment_numbers() # Output: Numbers: [0, 1, 2]\n",
"increment_numbers() # Output: Numbers: [0, 1, 2]"
]
}
],
"metadata": {
Expand Down

0 comments on commit e5ed341

Please sign in to comment.