From 5a2ddec9b2fa31c73b1d3d77ea4336a59427b4de Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 5 Sep 2022 03:00:56 -0700 Subject: [PATCH] Use tomllib on Python 3.11 (#4476) * Use tomllib on Python 3.11 * changelog --- changes/4476-hauntsaninja.md | 1 + pydantic/mypy.py | 26 +++++++++++++++----------- 2 files changed, 16 insertions(+), 11 deletions(-) create mode 100644 changes/4476-hauntsaninja.md diff --git a/changes/4476-hauntsaninja.md b/changes/4476-hauntsaninja.md new file mode 100644 index 0000000000..37b4cf5b25 --- /dev/null +++ b/changes/4476-hauntsaninja.md @@ -0,0 +1 @@ +Use `tomllib` on Python 3.11 when parsing `mypy` configuration. diff --git a/pydantic/mypy.py b/pydantic/mypy.py index 2619259094..8835275f51 100644 --- a/pydantic/mypy.py +++ b/pydantic/mypy.py @@ -1,3 +1,4 @@ +import sys from configparser import ConfigParser from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type as TypingType, Union @@ -820,18 +821,21 @@ def parse_toml(config_file: str) -> Optional[Dict[str, Any]]: return None read_mode = 'rb' - try: - import tomli as toml_ - except ImportError: - # older versions of mypy have toml as a dependency, not tomli - read_mode = 'r' + if sys.version_info >= (3, 11): + import tomllib as toml_ + else: try: - import toml as toml_ # type: ignore[no-redef] - except ImportError: # pragma: no cover - import warnings - - warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.') - return None + import tomli as toml_ + except ImportError: + # older versions of mypy have toml as a dependency, not tomli + read_mode = 'r' + try: + import toml as toml_ # type: ignore[no-redef] + except ImportError: # pragma: no cover + import warnings + + warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.') + return None with open(config_file, read_mode) as rf: return toml_.load(rf) # type: ignore[arg-type]