From 7a42cf636eed5b274168caf4ace0ab17e2514cf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=98=E5=85=B8?= Date: Sun, 9 Aug 2026 08:38:53 +0800 Subject: [PATCH] fix: guard TOML config read when tomli/tomllib is unavailable configuration.py imported tomllib (or tomli as tomllib) under contextlib.suppress(ImportError), then used tomllib.load unconditionally. On Python < 3.11 without the tomli backport, the import fails silently, leaving tomllib unbound, so any run with a pyproject.toml crashes with NameError: name 'tomllib' is not defined (#368). 1.7.7 guarded this with a TOMLI_INSTALLED check; the 1.7.8 refactor dropped it. Use a try/except that binds tomllib to None when neither is available, and skip reading the TOML configuration in that case (matching 1.7.7, which ran cleanly on the same interpreter) instead of crashing. Drops the now-unused contextlib import. Closes #368 --- src/docformatter/configuration.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/docformatter/configuration.py b/src/docformatter/configuration.py index 8342a1c..3fe45ee 100644 --- a/src/docformatter/configuration.py +++ b/src/docformatter/configuration.py @@ -28,19 +28,22 @@ # Standard Library Imports import argparse -import contextlib import os import sys from configparser import ConfigParser from typing import Dict, Sequence, Union -with contextlib.suppress(ImportError): +try: if sys.version_info >= (3, 11): # Standard Library Imports import tomllib else: # Third Party Imports import tomli as tomllib +except ImportError: + # Neither the stdlib tomllib (Python < 3.11) nor the tomli backport is + # available; TOML configuration files are skipped in that case. See #368. + tomllib = None # docformatter Package Imports from docformatter import __pkginfo__ @@ -340,6 +343,11 @@ def _do_read_configuration_file(self) -> None: def _do_read_toml_configuration(self) -> None: """Load configuration information from a *.toml file.""" + if tomllib is None: + # tomli/tomllib is not installed (Python < 3.11 without the tomli + # backport); skip reading TOML configuration rather than crashing + # with a NameError. See #368. + return with open(self.config_file, "rb") as f: config = tomllib.load(f)