はじめに
これまでの番外編でモデル層(database.py・note_model.py・schedule_model.py)のスタイル改善を完了しました。今回からビュー層の見直しに入ります。最初に取り上げるのは、月間カレンダーの表示を担当する calendar_view.py です。
このファイルはこれまでのモデル層のファイルと比べて行数が多く、特に render メソッドが約60行に及んでいます。型ヒント・docstring・Callable の具体化・メソッドの分割・tk.Label の引数整形という5つの観点から改善を行います。
1. 改善箇所
まず、改善前のコードを確認します。
改善前
""" カレンダーグリッドの表示を担当するViewクラス。 """ import tkinter as tk import calendar from datetime import datetime, date from typing import Callable import jpholiday from config import DATE_FONT_SIZE, CELL_HEIGHT class CalendarView: """ 月間カレンダーのヘッダー・グリッドウィジェットを管理するクラス。 ロジックは保持せず、描画とコールバックの口だけを提供する。 """ def __init__(self, parent, colors: dict): """ :param parent: 親ウィジェット(PanedWindowペイン) :param colors: テーマカラー辞書 """ self.colors = colors self.container = tk.Frame(parent, bg=colors["frame_bg"]) header = tk.Frame(self.container, bg=colors["frame_bg"], pady=5) header.pack(fill=tk.X) self._prev_btn = tk.Label( header, text="< 前月", font=("Arial", 10), width=8, bg=colors["button_bg"], fg=colors["button_fg"], cursor="hand2", padx=5, pady=2, highlightthickness=0, highlightbackground=colors["button_fg"] ) self._prev_btn.pack(side=tk.LEFT, padx=20) # ... (以下略) def bind_prev(self, callback: Callable) -> None: """「前月」ボタンクリック時のコールバックを登録する。""" self._prev_btn.bind("<Button-1>", lambda e: callback()) def bind_next(self, callback: Callable) -> None: """「次月」ボタンクリック時のコールバックを登録する。""" self._next_btn.bind("<Button-1>", lambda e: callback()) def render(self, year: int, month: int, selected_date: date, on_date_click: Callable) -> None: """ カレンダーグリッドを再描画する。 :param year: 表示年 :param month: 表示月 :param selected_date: 選択中の日付(ハイライト用) :param on_date_click: 日付セルクリック時のコールバック (date, holiday_name) -> None """ # 約60行の処理が続く...
改善ポイントは以下の5点です。
2. 改善点① __init__ に型ヒントと -> None がない
問題
parent に型ヒントがなく、colors が dict と不具体です。また -> None も省略されています。これまでのモデル層の改善と同様のパターンです。
# ❌ 現状 def __init__(self, parent, colors: dict):
改善方法
# ✅ 推奨 def __init__(self, parent: tk.Widget, colors: dict[str, str]) -> None:
3. 改善点② docstring が Sphinx スタイル(__init__ / render)
問題
__init__ と render が :param: の Sphinx スタイルで書かれています。番外編4・番外編9・番外編10と同様に、Google スタイルに統一します。
# ❌ 現状:Sphinxスタイル def __init__(self, parent, colors: dict): """ :param parent: 親ウィジェット(PanedWindowペイン) :param colors: テーマカラー辞書 """
改善方法
__init__ には概要を1行目に加え、Args: セクションを続けます。
# ✅ 推奨:Googleスタイル def __init__(self, parent: tk.Widget, colors: dict[str, str]) -> None: """カレンダーグリッドのヘッダーと描画エリアを初期化する。 Args: parent: 親ウィジェット(PanedWindowペイン)。 colors: テーマカラー辞書。 """
render も同様に変更します。引数が多いため、合わせて1引数1行の改行スタイルも適用します。
# ✅ 推奨:Googleスタイル + 引数改行 def render( self, year: int, month: int, selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """カレンダーグリッドを再描画する。 Args: year: 表示年。 month: 表示月。 selected_date: 選択中の日付(ハイライト用)。 on_date_click: 日付セルクリック時のコールバック。 """
4. 改善点③ Callable の型が曖昧
問題
bind_prev / bind_next / render の Callable に引数・戻り値の情報がなく、どんな関数を渡すべきかがコードから読み取れません。
# ❌ 現状:引数・戻り値が不明 def bind_prev(self, callback: Callable) -> None: def bind_next(self, callback: Callable) -> None: def render(self, ..., on_date_click: Callable) -> None:
改善方法
各コールバックが受け取る引数と戻り値を明記します。
# ✅ 推奨:シグネチャまで明記 def bind_prev(self, callback: Callable[[], None]) -> None: def bind_next(self, callback: Callable[[], None]) -> None: def render(self, ..., on_date_click: Callable[[date, str], None]) -> None:
5. 改善点④ render メソッドが長すぎる
問題
render メソッドは約60行あり、以下の4つの責務が1つのメソッドに混在しています。
- 曜日ヘッダーの描画
- 日付セル全体のループ処理
- 1つの日付セルの描画とクリックイベントの設定
- グリッドの伸縮設定
このままでは pylint の too-many-locals(R0914)や too-many-branches(R0912)の警告にも抵触します。
改善方法
責務ごとに4つのプライベートメソッドに切り出します。render メソッド自体はそれらを呼び出す「司令塔」として整理します。
def render( self, year: int, month: int, selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """カレンダーグリッドを再描画する。""" for widget in self._grid_frame.winfo_children(): widget.destroy() self._grid_frame.config(bg=self.colors["frame_fg"]) self._month_label.config(text=f"{year}年{month}月") self._render_weekday_header() cal = calendar.Calendar(firstweekday=6) month_days = cal.monthdayscalendar(year, month) self._render_day_cells(year, month, month_days, selected_date, on_date_click) self._configure_grid(month_days) def _render_weekday_header(self) -> None: """曜日ヘッダー行を描画する。""" weekdays = ["日", "月", "火", "水", "木", "金", "土"] day_fg_colors = [ self.colors["cal_fg_sun"], *[self.colors["cal_fg_not_sunsat"]] * 5, self.colors["cal_fg_sat"], ] for i, label in enumerate(weekdays): tk.Label( self._grid_frame, text=label, font=("Arial", 11, "bold"), bg=self.colors["cal_bg"], fg=day_fg_colors[i], width=8, height=1, ).grid(row=0, column=i, sticky="nsew", padx=1, pady=1) def _render_day_cells( self, year: int, month: int, month_days: list[list[int]], selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """日付セル全体をループして描画する。""" for week_idx, week in enumerate(month_days, start=1): for day_idx, day in enumerate(week): cell = tk.Frame( self._grid_frame, bg=self.colors["cal_bg"], height=CELL_HEIGHT, width=100, ) cell.grid( row=week_idx, column=day_idx, sticky="nsew", padx=1, pady=1, ) cell.grid_propagate(False) cell.pack_propagate(False) if day == 0: continue self._render_day_cell( cell, year, month, day, day_idx, selected_date, on_date_click ) def _render_day_cell( self, cell: tk.Frame, year: int, month: int, day: int, day_idx: int, selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """1つの日付セルを描画する。""" date_obj = datetime(year, month, day) holiday_name = jpholiday.is_holiday_name(date_obj.date()) if holiday_name or day_idx == 0: fg = self.colors["cal_fg_sun"] elif day_idx == 6: fg = self.colors["cal_fg_sat"] else: fg = self.colors["cal_fg_not_sunsat"] date_lbl = tk.Label( cell, text=str(day), font=("Arial", DATE_FONT_SIZE), bg=self.colors["cal_bg"], fg=fg, ) for target in (cell, date_lbl): target.bind( "<Button-1>", lambda e, d=date_obj.date(), h=holiday_name: on_date_click(d, h), ) target.config(cursor="hand2") date_lbl.pack(side=tk.TOP, pady=(5, 0)) if date_obj.date() == selected_date: sel_bg = self.colors["cal_selected"] cell.config(bg=sel_bg) date_lbl.config(bg=sel_bg) def _configure_grid(self, month_days: list[list[int]]) -> None: """グリッドの伸縮設定を行う。""" for i in range(7): self._grid_frame.columnconfigure(i, weight=1) for i in range(len(month_days) + 1): self._grid_frame.rowconfigure(i, weight=1)
render 自体が約10行になり、各プライベートメソッドが単一の責務を持つ構造になりました。
6. 改善点⑤ tk.Label の引数が1行に詰め込まれている
問題
番外編1(tkinter ウィジェット編)で整理した通り、tk.Label の引数が複数行にまたがりながらも、途中で改行がなく可読性が低い状態です。_prev_btn / _month_label / _next_btn / date_lbl の計4箇所に同様の問題があります。
# ❌ 現状:引数が詰め込まれている self._prev_btn = tk.Label( header, text="< 前月", font=("Arial", 10), width=8, bg=colors["button_bg"], fg=colors["button_fg"], cursor="hand2", padx=5, pady=2, highlightthickness=0, highlightbackground=colors["button_fg"] )
改善方法
1引数1行、末尾カンマ、閉じ括弧を呼び出し元と同じインデントに統一します。
# ✅ 推奨:1引数1行 self._prev_btn = tk.Label( header, text="< 前月", font=("Arial", 10), width=8, bg=colors["button_bg"], fg=colors["button_fg"], cursor="hand2", padx=5, pady=2, highlightthickness=0, highlightbackground=colors["button_fg"], )
_month_label / _next_btn / date_lbl も同様に適用します。
7. 改善後の完成コード
5点の改善を適用した calendar_view.py の完成形は以下のとおりです。
改善後
""" カレンダーグリッドの表示を担当するViewクラス。 """ import tkinter as tk import calendar from datetime import datetime, date from typing import Callable import jpholiday from config import DATE_FONT_SIZE, CELL_HEIGHT class CalendarView: """ 月間カレンダーのヘッダー・グリッドウィジェットを管理するクラス。 ロジックは保持せず、描画とコールバックの口だけを提供する。 """ def __init__(self, parent: tk.Widget, colors: dict[str, str]) -> None: """カレンダーグリッドのヘッダーと描画エリアを初期化する。 Args: parent: 親ウィジェット(PanedWindowペイン)。 colors: テーマカラー辞書。 """ self.colors = colors self.container = tk.Frame(parent, bg=colors["frame_bg"]) header = tk.Frame(self.container, bg=colors["frame_bg"], pady=5) header.pack(fill=tk.X) self._prev_btn = tk.Label( header, text="< 前月", font=("Arial", 10), width=8, bg=colors["button_bg"], fg=colors["button_fg"], cursor="hand2", padx=5, pady=2, highlightthickness=0, highlightbackground=colors["button_fg"], ) self._prev_btn.pack(side=tk.LEFT, padx=20) self._month_label = tk.Label( header, text="", font=("Arial", 10), width=15, bg=colors["button_bg"], fg=colors["button_fg"], padx=5, pady=2, highlightthickness=0, highlightbackground=colors["button_fg"], ) self._month_label.pack(side=tk.LEFT, expand=True) self._next_btn = tk.Label( header, text="次月 >", font=("Arial", 10), width=8, bg=colors["button_bg"], fg=colors["button_fg"], cursor="hand2", padx=5, pady=2, highlightthickness=0, highlightbackground=colors["button_fg"], ) self._next_btn.pack(side=tk.RIGHT, padx=20) self._grid_frame = tk.Frame(self.container, bg=colors["frame_bg"]) self._grid_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # ── コールバック登録 ───────────────────────────────────────────── def bind_prev(self, callback: Callable[[], None]) -> None: """「前月」ボタンクリック時のコールバックを登録する。""" self._prev_btn.bind("<Button-1>", lambda e: callback()) def bind_next(self, callback: Callable[[], None]) -> None: """「次月」ボタンクリック時のコールバックを登録する。""" self._next_btn.bind("<Button-1>", lambda e: callback()) # ── 描画 ───────────────────────────────────────────────────────── def render( self, year: int, month: int, selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """カレンダーグリッドを再描画する。 Args: year: 表示年。 month: 表示月。 selected_date: 選択中の日付(ハイライト用)。 on_date_click: 日付セルクリック時のコールバック。 """ for widget in self._grid_frame.winfo_children(): widget.destroy() self._grid_frame.config(bg=self.colors["frame_fg"]) self._month_label.config(text=f"{year}年{month}月") self._render_weekday_header() cal = calendar.Calendar(firstweekday=6) month_days = cal.monthdayscalendar(year, month) self._render_day_cells(year, month, month_days, selected_date, on_date_click) self._configure_grid(month_days) def _render_weekday_header(self) -> None: """曜日ヘッダー行を描画する。""" weekdays = ["日", "月", "火", "水", "木", "金", "土"] day_fg_colors = [ self.colors["cal_fg_sun"], *[self.colors["cal_fg_not_sunsat"]] * 5, self.colors["cal_fg_sat"], ] for i, label in enumerate(weekdays): tk.Label( self._grid_frame, text=label, font=("Arial", 11, "bold"), bg=self.colors["cal_bg"], fg=day_fg_colors[i], width=8, height=1, ).grid(row=0, column=i, sticky="nsew", padx=1, pady=1) def _render_day_cells( self, year: int, month: int, month_days: list[list[int]], selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """日付セル全体をループして描画する。""" for week_idx, week in enumerate(month_days, start=1): for day_idx, day in enumerate(week): cell = tk.Frame( self._grid_frame, bg=self.colors["cal_bg"], height=CELL_HEIGHT, width=100, ) cell.grid( row=week_idx, column=day_idx, sticky="nsew", padx=1, pady=1, ) cell.grid_propagate(False) cell.pack_propagate(False) if day == 0: continue self._render_day_cell( cell, year, month, day, day_idx, selected_date, on_date_click ) def _render_day_cell( self, cell: tk.Frame, year: int, month: int, day: int, day_idx: int, selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """1つの日付セルを描画する。""" date_obj = datetime(year, month, day) holiday_name = jpholiday.is_holiday_name(date_obj.date()) if holiday_name or day_idx == 0: fg = self.colors["cal_fg_sun"] elif day_idx == 6: fg = self.colors["cal_fg_sat"] else: fg = self.colors["cal_fg_not_sunsat"] date_lbl = tk.Label( cell, text=str(day), font=("Arial", DATE_FONT_SIZE), bg=self.colors["cal_bg"], fg=fg, ) for target in (cell, date_lbl): target.bind( "<Button-1>", lambda e, d=date_obj.date(), h=holiday_name: on_date_click(d, h), ) target.config(cursor="hand2") date_lbl.pack(side=tk.TOP, pady=(5, 0)) if date_obj.date() == selected_date: sel_bg = self.colors["cal_selected"] cell.config(bg=sel_bg) date_lbl.config(bg=sel_bg) def _configure_grid(self, month_days: list[list[int]]) -> None: """グリッドの伸縮設定を行う。""" for i in range(7): self._grid_frame.columnconfigure(i, weight=1) for i in range(len(month_days) + 1): self._grid_frame.rowconfigure(i, weight=1)
8. pylint での確認と追加リファクタリング
修正後にプロジェクトルートから pylint を実行します。
% PYTHONPATH=. pylint views/calendar_view.py ************* Module calendar_view views/calendar_view.py:173:4: R0913: Too many arguments (8/6) (too-many-arguments) views/calendar_view.py:173:4: R0917: Too many positional arguments (8/6) (too-many-positional-arguments) ------------------------------------------------------------------ Your code has been rated at 9.72/10 (previous run: 9.05/10, +0.67)
10.00/10 にならず、_render_day_cell メソッドで警告が出ました。
警告の原因
_render_day_cell は self を除いて cell / year / month / day / day_idx / selected_date / on_date_click の 7引数 あります。.pylintrc の現在の上限は schedule_model.py の対応で設定した 6 のため、両方の制限に抵触しています。
対処方法:.pylintrc の上限引き上げではなくリファクタリングで解決
year / month / day という密接に関連する3つの引数は、そもそも datetime オブジェクト1つに集約できます。呼び出し元の _render_day_cells で date_obj を生成してから渡す形に変更することで、引数を7→5に削減します。
.pylintrc の上限を引き上げる方法もありますが、それは設計の問題を隠すだけです。今回はリファクタリングによる引数削減を選びます。
# ✅ _render_day_cells 側:date_obj を生成して渡す def _render_day_cells( self, year: int, month: int, month_days: list[list[int]], selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """日付セル全体をループして描画する。""" for week_idx, week in enumerate(month_days, start=1): for day_idx, day in enumerate(week): cell = tk.Frame( self._grid_frame, bg=self.colors["cal_bg"], height=CELL_HEIGHT, width=100, ) cell.grid( row=week_idx, column=day_idx, sticky="nsew", padx=1, pady=1, ) cell.grid_propagate(False) cell.pack_propagate(False) if day == 0: continue date_obj = datetime(year, month, day) # ← ここで生成して渡す self._render_day_cell( cell, date_obj, day_idx, selected_date, on_date_click ) # ✅ _render_day_cell 側:year/month/day の代わりに date_obj を受け取る # self を除く引数が 5つ → 警告なし def _render_day_cell( self, cell: tk.Frame, date_obj: datetime, # ← year/month/day の3引数を1つに集約 day_idx: int, selected_date: date, on_date_click: Callable[[date, str], None], ) -> None: """1つの日付セルを描画する。""" holiday_name = jpholiday.is_holiday_name(date_obj.date()) if holiday_name or day_idx == 0: fg = self.colors["cal_fg_sun"] elif day_idx == 6: fg = self.colors["cal_fg_sat"] else: fg = self.colors["cal_fg_not_sunsat"] date_lbl = tk.Label( cell, text=str(date_obj.day), font=("Arial", DATE_FONT_SIZE), bg=self.colors["cal_bg"], fg=fg, ) for target in (cell, date_lbl): target.bind( "<Button-1>", lambda e, d=date_obj.date(), h=holiday_name: on_date_click(d, h), ) target.config(cursor="hand2") date_lbl.pack(side=tk.TOP, pady=(5, 0)) if date_obj.date() == selected_date: sel_bg = self.colors["cal_selected"] cell.config(bg=sel_bg) date_lbl.config(bg=sel_bg)
リファクタリング後に再度 pylint を実行します。
% PYTHONPATH=. pylint views/calendar_view.py -------------------------------------------------------------------- Your code has been rated at 10.00/10 (previous run: 9.72/10, +0.28)
10.00/10 を達成できました。
おわりに
今回は calendar_view.py を対象に、型ヒントの追加・docstring のスタイル統一・Callable の具体化・render メソッドの分割・tk.Label の引数整形という5点の改善を行いました。
また、pylint の実行で _render_day_cell の引数過多という追加の問題が見つかりました。.pylintrc の上限引き上げで対処することもできましたが、year / month / day を datetime オブジェクトに集約するリファクタリングで解決しました。警告を「隠す」のではなく「設計の改善で解消する」という判断が、コードの質の向上につながります。
次回は、メモエリアの表示を担当する note_view.py のスタイル改善を進めていきます。