diff --git a/python-refactoring/.pre-commit-config.yaml b/python-refactoring/.pre-commit-config.yaml new file mode 100644 index 0000000000..8346c8c589 --- /dev/null +++ b/python-refactoring/.pre-commit-config.yaml @@ -0,0 +1,9 @@ +repos: +- repo: local + hooks: + - id: wily + name: wily + entry: wily diff + verbose: true + language: python + additional_dependencies: [wily==1.25.0] diff --git a/python-refactoring/README.md b/python-refactoring/README.md new file mode 100644 index 0000000000..6911fafa7d --- /dev/null +++ b/python-refactoring/README.md @@ -0,0 +1,45 @@ +# Refactoring Python Applications for Simplicity + +This folder provides the code examples for the Real Python tutorial [Refactoring Python Applications for Simplicity](https://realpython.com/python-refactoring/). + +## Setup + +The code requires Python 3.11 or later. Create and activate a virtual environment, then install the pinned tools: + +```sh +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +`radon` is pinned to 5.1.0 because `wily` 1.25.0 requires the 5.1 series. + +## Usage + +### Measuring Complexity + +- `cyclomatic_example.py`: The example script that you analyze with `radon`. The `# fmt: off` line keeps the tutorial's layout, so the line numbers and metrics match the article. + +```sh +(venv) $ radon cc cyclomatic_example.py -s +(venv) $ radon hal cyclomatic_example.py +(venv) $ radon mi cyclomatic_example.py -s +``` + +- `.pre-commit-config.yaml`: A `pre-commit` hook that runs `wily diff` on the files you commit. Copy it into your project, run `wily build ` once, then run `pre-commit install`. + +### Complexity Anti-Patterns + +- `contains_errors.py`: The nested `contains_errors()` function and its flat, early-return refactoring +- `network_data.py`: The nested Tokyo Metro dictionary shared by the next two scripts +- `find_line.py`: Looks up a line by number with a list comprehension +- `network_query.py`: Runs the same queries with JMESPath +- `line_class.py`: The boilerplate `Line` and `Network` classes +- `line_dataclass.py`: `Line` as a data class +- `line_attrs.py`: `Line` with `attrs`, including a validator + +Run any script directly: + +```sh +(venv) $ python network_query.py +``` diff --git a/python-refactoring/contains_errors.py b/python-refactoring/contains_errors.py new file mode 100644 index 0000000000..9f0cc74c8c --- /dev/null +++ b/python-refactoring/contains_errors.py @@ -0,0 +1,21 @@ +def contains_errors_nested(data): + if isinstance(data, list): + for item in data: + if isinstance(item, str): + if item == "error": + return True + return False + + +def contains_errors(data): + if not isinstance(data, list): + return False + return "error" in data + + +if __name__ == "__main__": + samples = [["ok", "error"], ["ok", 42], "error", [], [1, "error", None]] + for sample in samples: + nested = contains_errors_nested(sample) + flat = contains_errors(sample) + print(f"{sample!r}: nested={nested}, flat={flat}") diff --git a/python-refactoring/cyclomatic_example.py b/python-refactoring/cyclomatic_example.py new file mode 100644 index 0000000000..222ecd1467 --- /dev/null +++ b/python-refactoring/cyclomatic_example.py @@ -0,0 +1,17 @@ +# fmt: off +import sys + +def main(): + if len(sys.argv) > 1: # 1 + filepath = sys.argv[1] + else: + print("Provide a file path") + sys.exit(1) + if filepath: # 2 + with open(filepath) as fp: # 3 + for line in fp.readlines(): # 4 + if line != "\n": # 5 + print(line, end="") + +if __name__ == "__main__": # Ignored. + main() diff --git a/python-refactoring/find_line.py b/python-refactoring/find_line.py new file mode 100644 index 0000000000..15309b4fad --- /dev/null +++ b/python-refactoring/find_line.py @@ -0,0 +1,13 @@ +from network_data import data + + +def find_line_by_number(data, number): + matches = [line for line in data if line["number"] == number] + if len(matches) > 0: + return matches[0] + else: + raise ValueError(f"Line {number} does not exist.") + + +if __name__ == "__main__": + print(find_line_by_number(data["network"]["lines"], 3)) diff --git a/python-refactoring/line_attrs.py b/python-refactoring/line_attrs.py new file mode 100644 index 0000000000..07b4e8ae27 --- /dev/null +++ b/python-refactoring/line_attrs.py @@ -0,0 +1,18 @@ +from attrs import define, field, validators + + +@define +class Line: + name_en: str + name_jp: str + color: str + number: int = field(validator=validators.instance_of(int)) + sign: str = field(default="") + + +if __name__ == "__main__": + print(Line("Ginza", "銀座線", "orange", 3)) + try: + Line("Ginza", "銀座線", "orange", "3") + except TypeError as error: + print(f"TypeError: {error}") diff --git a/python-refactoring/line_class.py b/python-refactoring/line_class.py new file mode 100644 index 0000000000..8e2ab6df0a --- /dev/null +++ b/python-refactoring/line_class.py @@ -0,0 +1,35 @@ +class Line: + def __init__( + self, name_en: str, name_jp: str, color: str, number: int, sign: str + ): + self.name_en = name_en + self.name_jp = name_jp + self.color = color + self.number = number + self.sign = sign + + def __repr__(self): + return ( + f"" + ) + + def __str__(self): + return f"The {self.name_en} line" + + +class Network: + def __init__(self, lines: list[Line]): + self._lines = lines + + @property + def lines(self) -> list[Line]: + return self._lines + + +if __name__ == "__main__": + line = Line("Marunouchi", "丸ノ内線", "red", 4, "M") + network = Network([line]) + print(repr(line)) + print(line) + print(network.lines) diff --git a/python-refactoring/line_dataclass.py b/python-refactoring/line_dataclass.py new file mode 100644 index 0000000000..5061fb879a --- /dev/null +++ b/python-refactoring/line_dataclass.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass + + +@dataclass +class Line: + name_en: str + name_jp: str + color: str + number: int + sign: str + + +if __name__ == "__main__": + line = Line("Marunouchi", "丸ノ内線", "red", 4, "M") + print(repr(line.color)) + line2 = Line("Marunouchi", "丸ノ内線", "red", 4, "M") + print(line == line2) diff --git a/python-refactoring/network_data.py b/python-refactoring/network_data.py new file mode 100644 index 0000000000..8bb673e6e4 --- /dev/null +++ b/python-refactoring/network_data.py @@ -0,0 +1,20 @@ +data = { + "network": { + "lines": [ + { + "name_en": "Ginza", + "name_jp": "銀座線", + "color": "orange", + "number": 3, + "sign": "G", + }, + { + "name_en": "Marunouchi", + "name_jp": "丸ノ内線", + "color": "red", + "number": 4, + "sign": "M", + }, + ] + } +} diff --git a/python-refactoring/network_query.py b/python-refactoring/network_query.py new file mode 100644 index 0000000000..e80642b4f6 --- /dev/null +++ b/python-refactoring/network_query.py @@ -0,0 +1,8 @@ +import jmespath + +from network_data import data + +print(jmespath.search("network.lines", data)) +print(jmespath.search("network.lines[*].number", data)) +print(jmespath.search("network.lines[?number==`3`]", data)) +print(jmespath.search("network.lines[?number==`3`].color", data)) diff --git a/python-refactoring/requirements.txt b/python-refactoring/requirements.txt new file mode 100644 index 0000000000..76b893fd7f --- /dev/null +++ b/python-refactoring/requirements.txt @@ -0,0 +1,7 @@ +attrs==26.1.0 +jmespath==1.1.0 +pre-commit==4.7.0 +pylint==4.1.5 +radon==5.1.0 +rope==1.16.0 +wily==1.25.0