Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions python-refactoring/.pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -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]
45 changes: 45 additions & 0 deletions python-refactoring/README.md
Original file line number Diff line number Diff line change
@@ -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 <folder>` 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
```
21 changes: 21 additions & 0 deletions python-refactoring/contains_errors.py
Original file line number Diff line number Diff line change
@@ -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}")
17 changes: 17 additions & 0 deletions python-refactoring/cyclomatic_example.py
Original file line number Diff line number Diff line change
@@ -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()
13 changes: 13 additions & 0 deletions python-refactoring/find_line.py
Original file line number Diff line number Diff line change
@@ -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))
18 changes: 18 additions & 0 deletions python-refactoring/line_attrs.py
Original file line number Diff line number Diff line change
@@ -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}")
35 changes: 35 additions & 0 deletions python-refactoring/line_class.py
Original file line number Diff line number Diff line change
@@ -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"<Line {self.name_en} color='{self.color}' "
f"number={self.number} sign='{self.sign}'>"
)

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)
17 changes: 17 additions & 0 deletions python-refactoring/line_dataclass.py
Original file line number Diff line number Diff line change
@@ -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)
20 changes: 20 additions & 0 deletions python-refactoring/network_data.py
Original file line number Diff line number Diff line change
@@ -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",
},
]
}
}
8 changes: 8 additions & 0 deletions python-refactoring/network_query.py
Original file line number Diff line number Diff line change
@@ -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))
7 changes: 7 additions & 0 deletions python-refactoring/requirements.txt
Original file line number Diff line number Diff line change
@@ -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
Loading