Skip to content

Commit e4f4ea4

Browse files
lint: Catch use of [] or {} as default parameter values in Python functions
1 parent 25dd867 commit e4f4ea4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/usr/bin/env bash
2+
#
3+
# Copyright (c) 2019 The Bitcoin Core developers
4+
# Distributed under the MIT software license, see the accompanying
5+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
6+
#
7+
# Detect when a mutable list or dict is used as a default parameter value in a Python function.
8+
9+
export LC_ALL=C
10+
EXIT_CODE=0
11+
OUTPUT=$(git grep -E '^\s*def [a-zA-Z0-9_]+\(.*=\s*(\[|\{)' -- "*.py")
12+
if [[ ${OUTPUT} != "" ]]; then
13+
echo "A mutable list or dict seems to be used as default parameter value:"
14+
echo
15+
echo "${OUTPUT}"
16+
echo
17+
cat << EXAMPLE
18+
This is how mutable list and dict default parameter values behave:
19+
20+
>>> def f(i, j=[], k={}):
21+
... j.append(i)
22+
... k[i] = True
23+
... return j, k
24+
...
25+
>>> f(1)
26+
([1], {1: True})
27+
>>> f(1)
28+
([1, 1], {1: True})
29+
>>> f(2)
30+
([1, 1, 2], {1: True, 2: True})
31+
32+
The intended behaviour was likely:
33+
34+
>>> def f(i, j=None, k=None):
35+
... if j is None:
36+
... j = []
37+
... if k is None:
38+
... k = {}
39+
... j.append(i)
40+
... k[i] = True
41+
... return j, k
42+
...
43+
>>> f(1)
44+
([1], {1: True})
45+
>>> f(1)
46+
([1], {1: True})
47+
>>> f(2)
48+
([2], {2: True})
49+
EXAMPLE
50+
EXIT_CODE=1
51+
fi
52+
exit ${EXIT_CODE}

0 commit comments

Comments
 (0)