diff --git a/book/pythontricks/Chapter.ipynb b/book/pythontricks/Chapter.ipynb index 4e91ec7..2c6ecd2 100644 --- a/book/pythontricks/Chapter.ipynb +++ b/book/pythontricks/Chapter.ipynb @@ -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": {