From 7df4b5a3682053f4bf9b6fbe55da24e201f6cc59 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 28 Aug 2017 00:58:58 +0530 Subject: [PATCH] Add common practice to default mutable argument example. --- wtfpy.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/wtfpy.md b/wtfpy.md index 3ea3062..5d9281f 100755 --- a/wtfpy.md +++ b/wtfpy.md @@ -280,6 +280,16 @@ def some_func(default_arg=[]): (['some_string', 'some_string'],) ``` +A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Examlple: + +```py +def some_func(default_arg=None): + if not default_arg: + default_arg = [] + default_arg.append("some_string") + return default_arg +``` + ## You can't change the values contained in tuples because they're immutable.. Oh really? @@ -306,6 +316,8 @@ Quoting from https://docs.python.org/2/reference/datamodel.html > Immutable sequences An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.) +## + # Contributing All patches are Welcome! Filing an issue first before submitting a patch will be appreciated :)