Skip to content

Commit

Permalink
Merge bitcoin/bitcoin#24800: lint: convert lint-python-mutable-defaul…
Browse files Browse the repository at this point in the history
…t-parameters.sh to Python

e8e48fa Converted lint-python-mutable-default-parameters.sh to python (TakeshiMusgrave)

Pull request description:

  This converts one of the linter scripts to Python. Reference issue: bitcoin/bitcoin#24783

  The approach is to just call git grep using subprocess.run.

  Alternative approaches could be to use Python instead of git grep (I'm not sure how) or use ```pylint --disable=all --enable=W0102```, though that requires installation of pylint.

ACKs for top commit:
  MarcoFalke:
    review ACK e8e48fa

Tree-SHA512: 7f6f4887dee02c9751b225a6a131fb705868859c4a9af25bb3485cda2358650486b110f17adf89d96a20f212d7d94899922a07aab12c8dc11984cfd5feb7a076
  • Loading branch information
MarcoFalke committed Apr 11, 2022
2 parents cd110cd + e8e48fa commit 22e3b6f
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 52 deletions.
72 changes: 72 additions & 0 deletions test/lint/lint-python-mutable-default-parameters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
#
# 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.
"""

import subprocess
import sys


def main():
command = [
"git",
"grep",
"-E",
r"^\s*def [a-zA-Z0-9_]+\(.*=\s*(\[|\{)",
"--",
"*.py",
]
output = subprocess.run(command, stdout=subprocess.PIPE, universal_newlines=True)
if len(output.stdout) > 0:
error_msg = (
"A mutable list or dict seems to be used as default parameter value:\n\n"
f"{output.stdout}\n"
f"{example()}"
)
print(error_msg)
sys.exit(1)
else:
sys.exit(0)


def example():
return """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})"""


if __name__ == "__main__":
main()
52 changes: 0 additions & 52 deletions test/lint/lint-python-mutable-default-parameters.sh

This file was deleted.

0 comments on commit 22e3b6f

Please sign in to comment.