From 5b81741d5a559e5c87c3eb1a638e6f2ceb37b2ca Mon Sep 17 00:00:00 2001 From: Devyn Collier Johnson Date: Sat, 19 May 2018 17:53:16 -0500 Subject: [PATCH] Add support for comments containing Unicode When using Flake8 (with Flake8-Mypy) on Python scripts containing comments with Unicode comments, Flake8 crashes with a UnicodeEncodeError. The suggested code in my commit appears to resolve the issue without side-effects. --- flake8_mypy.py | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/flake8_mypy.py b/flake8_mypy.py index 5560f2b..0577ec6 100644 --- a/flake8_mypy.py +++ b/flake8_mypy.py @@ -183,15 +183,26 @@ def run(self) -> Iterator[_Flake8Error]: # Always put the file in a separate temporary directory to avoid # unexpected clashes with other .py and .pyi files in the same original # directory. - with TemporaryDirectory(prefix='flake8mypy_') as d: - with NamedTemporaryFile( - 'w', encoding='utf8', prefix='tmpmypy_', suffix='.py', dir=d - ) as f: - self.filename = f.name - for line in self.lines: - f.write(line) - f.flush() - yield from self._run() + try: + with TemporaryDirectory(prefix='flake8mypy_') as d: + with NamedTemporaryFile( + 'wt', prefix='tmpmypy_', suffix='.py', dir=d + ) as f: + self.filename = f.name + for line in self.lines: + f.write(line) + f.flush() + yield from self._run() + except UnicodeEncodeError: + with TemporaryDirectory(prefix='flake8mypy_') as d: + with NamedTemporaryFile( + 'wb', prefix='tmpmypy_', suffix='.py', dir=d + ) as f: + self.filename = f.name + for line in self.lines: + f.write(line.encode(r'utf8')) + f.flush() + yield from self._run() def _run(self) -> Iterator[_Flake8Error]: mypy_cmdline = self.build_mypy_cmdline(self.filename, self.options.mypy_config)