aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorpracticalswift <practicalswift@users.noreply.github.com>2019-08-25 21:49:32 +0000
committerpracticalswift <practicalswift@users.noreply.github.com>2019-08-26 10:53:10 +0000
commite4f4ea47ebf7774fb6f445adde7bf7ea71fa05a1 (patch)
treed7f2dde1f79ce434a7888dfcff4491ff021d4761
parent25dd86715039586d92176eee16e9c6644d2547f0 (diff)
downloadbitcoin-e4f4ea47ebf7774fb6f445adde7bf7ea71fa05a1.tar.xz
lint: Catch use of [] or {} as default parameter values in Python functions
-rwxr-xr-xtest/lint/lint-python-mutable-default-parameters.sh52
1 files changed, 52 insertions, 0 deletions
diff --git a/test/lint/lint-python-mutable-default-parameters.sh b/test/lint/lint-python-mutable-default-parameters.sh
new file mode 100755
index 0000000000..1f9f035d30
--- /dev/null
+++ b/test/lint/lint-python-mutable-default-parameters.sh
@@ -0,0 +1,52 @@
+#!/usr/bin/env bash
+#
+# Copyright (c) 2019 The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or http://www.opensource.org/licenses/mit-license.php.
+#
+# Detect when a mutable list or dict is used as a default parameter value in a Python function.
+
+export LC_ALL=C
+EXIT_CODE=0
+OUTPUT=$(git grep -E '^\s*def [a-zA-Z0-9_]+\(.*=\s*(\[|\{)' -- "*.py")
+if [[ ${OUTPUT} != "" ]]; then
+ echo "A mutable list or dict seems to be used as default parameter value:"
+ echo
+ echo "${OUTPUT}"
+ echo
+ cat << EXAMPLE
+This is how mutable list and dict default parameter values behave:
+
+>>> def f(i, j=[], k={}):
+... j.append(i)
+... k[i] = True
+... return j, k
+...
+>>> f(1)
+([1], {1: True})
+>>> f(1)
+([1, 1], {1: True})
+>>> f(2)
+([1, 1, 2], {1: True, 2: True})
+
+The intended behaviour was likely:
+
+>>> def f(i, j=None, k=None):
+... if j is None:
+... j = []
+... if k is None:
+... k = {}
+... j.append(i)
+... k[i] = True
+... return j, k
+...
+>>> f(1)
+([1], {1: True})
+>>> f(1)
+([1], {1: True})
+>>> f(2)
+([2], {2: True})
+EXAMPLE
+ EXIT_CODE=1
+fi
+exit ${EXIT_CODE}