Skip to content

Commit c54a843

Browse files
committed
Resolve EncodingWarnings
1 parent 99b04ca commit c54a843

File tree

5 files changed

+40
-7
lines changed

5 files changed

+40
-7
lines changed

mypy/build.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import errno
1818
import gc
1919
import json
20+
import locale
2021
import os
2122
import platform
2223
import re
@@ -1194,7 +1195,7 @@ def add_catch_all_gitignore(target_dir: str) -> None:
11941195
"""
11951196
gitignore = os.path.join(target_dir, ".gitignore")
11961197
try:
1197-
with open(gitignore, "x") as f:
1198+
with open(gitignore, "x", encoding=locale.getpreferredencoding(False)) as f:
11981199
print("# Automatically created by mypy", file=f)
11991200
print("*", file=f)
12001201
except FileExistsError:
@@ -1208,7 +1209,7 @@ def exclude_from_backups(target_dir: str) -> None:
12081209
"""
12091210
cachedir_tag = os.path.join(target_dir, "CACHEDIR.TAG")
12101211
try:
1211-
with open(cachedir_tag, "x") as f:
1212+
with open(cachedir_tag, "x", encoding=locale.getpreferredencoding(False)) as f:
12121213
f.write(
12131214
"""Signature: 8a477f597d28d172789f06886806bc55
12141215
# This file is a cache directory tag automatically created by mypy.
@@ -3600,7 +3601,7 @@ def record_missing_stub_packages(cache_dir: str, missing_stub_packages: set[str]
36003601
"""
36013602
fnam = missing_stubs_file(cache_dir)
36023603
if missing_stub_packages:
3603-
with open(fnam, "w") as f:
3604+
with open(fnam, "w", encoding=locale.getpreferredencoding(False)) as f:
36043605
for pkg in sorted(missing_stub_packages):
36053606
f.write(f"{pkg}\n")
36063607
else:

mypy/config_parser.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import argparse
44
import configparser
55
import glob as fileglob
6+
import locale
67
import os
78
import re
89
import sys
@@ -236,7 +237,7 @@ def parse_config_file(
236237
parser: MutableMapping[str, Any] = destructure_overrides(toml_data)
237238
config_types = toml_config_types
238239
else:
239-
config_parser.read(config_file)
240+
config_parser.read(config_file, encoding=locale.getpreferredencoding(False))
240241
parser = config_parser
241242
config_types = ini_config_types
242243
except (tomllib.TOMLDecodeError, configparser.Error, ConfigTOMLValueError) as err:

mypy/metastore.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from __future__ import annotations
1212

1313
import binascii
14+
import locale
1415
import os
1516
import time
1617
from abc import abstractmethod
@@ -93,7 +94,9 @@ def read(self, name: str) -> str:
9394
if not self.cache_dir_prefix:
9495
raise FileNotFoundError()
9596

96-
with open(os.path.join(self.cache_dir_prefix, name)) as f:
97+
with open(
98+
os.path.join(self.cache_dir_prefix, name), encoding=locale.getpreferredencoding(False)
99+
) as f:
97100
return f.read()
98101

99102
def write(self, name: str, data: str, mtime: float | None = None) -> bool:
@@ -106,7 +109,7 @@ def write(self, name: str, data: str, mtime: float | None = None) -> bool:
106109
tmp_filename = path + "." + random_string()
107110
try:
108111
os.makedirs(os.path.dirname(path), exist_ok=True)
109-
with open(tmp_filename, "w") as f:
112+
with open(tmp_filename, "w", encoding=locale.getpreferredencoding(False)) as f:
110113
f.write(data)
111114
os.replace(tmp_filename, path)
112115
if mtime is not None:

mypy/modulefinder.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import ast
99
import collections
1010
import functools
11+
import locale
1112
import os
1213
import re
1314
import subprocess
@@ -866,7 +867,7 @@ def load_stdlib_py_versions(custom_typeshed_dir: str | None) -> StdlibVersions:
866867

867868
versions_path = os.path.join(stdlib_dir, "VERSIONS")
868869
assert os.path.isfile(versions_path), (custom_typeshed_dir, versions_path, __file__)
869-
with open(versions_path) as f:
870+
with open(versions_path, encoding=locale.getpreferredencoding(False)) as f:
870871
for line in f:
871872
line = line.split("#")[0].strip()
872873
if line == "":

mypy/test/testapi.py

+27
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
from __future__ import annotations
22

3+
import shutil
4+
import subprocess
35
import sys
46
from io import StringIO
7+
from pathlib import Path
8+
from tempfile import NamedTemporaryFile, mkdtemp
59

610
import mypy.api
711
from mypy.test.helpers import Suite
@@ -13,12 +17,18 @@ def setUp(self) -> None:
1317
self.sys_stderr = sys.stderr
1418
sys.stdout = self.stdout = StringIO()
1519
sys.stderr = self.stderr = StringIO()
20+
with NamedTemporaryFile(delete=False) as tmp:
21+
tmp.write(b"x: int = 5\n")
22+
self.tmp_path = Path(tmp.name)
23+
self.tmp_cache_dir = Path(mkdtemp())
1624

1725
def tearDown(self) -> None:
1826
sys.stdout = self.sys_stdout
1927
sys.stderr = self.sys_stderr
2028
assert self.stdout.getvalue() == ""
2129
assert self.stderr.getvalue() == ""
30+
self.tmp_path.unlink()
31+
shutil.rmtree(self.tmp_cache_dir)
2232

2333
def test_capture_bad_opt(self) -> None:
2434
"""stderr should be captured when a bad option is passed."""
@@ -43,3 +53,20 @@ def test_capture_version(self) -> None:
4353
stdout, _, _ = mypy.api.run(["--version"])
4454
assert isinstance(stdout, str)
4555
assert stdout != ""
56+
57+
def test_default_encoding_warnings(self) -> None:
58+
"""No EncodingWarnings should be emitted."""
59+
for empty_cache in [True, False]:
60+
res = subprocess.run(
61+
[
62+
sys.executable,
63+
"-c",
64+
"import mypy.api;"
65+
"mypy.api.run("
66+
f"['--cache-dir', '{self.tmp_cache_dir}', '{self.tmp_path}']"
67+
")",
68+
],
69+
capture_output=True,
70+
env={"PYTHONWARNDEFAULTENCODING": "1"},
71+
)
72+
assert b"EncodingWarning" not in res.stderr

0 commit comments

Comments
 (0)