Skip to content
This repository was archived by the owner on Nov 3, 2023. It is now read-only.

Commit 5779900

Browse files
committed
Use tokenize.open to open files.
Without this, e.g. checking an UTF-8 file (with # encoding=utf-8) on Windows with Python 3 is broken (UnicodeDecodeError) because it's read as latin1.
1 parent cb94875 commit 5779900

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

pep257.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ def next(obj, default=nothing):
4949
return default
5050

5151

52+
# If possible (python >= 3.2) use tokenize.open to open files, so PEP 263
53+
# encoding markers are interpreted.
54+
try:
55+
tokenize_open = tk.open
56+
except AttributeError:
57+
tokenize_open = open
58+
59+
5260
__version__ = '0.5.0'
5361
__all__ = ('check', 'collect')
5462

@@ -671,7 +679,7 @@ def check(filenames, ignore=()):
671679
for filename in filenames:
672680
log.info('Checking file %s.', filename)
673681
try:
674-
with open(filename) as file:
682+
with tokenize_open(filename) as file:
675683
source = file.read()
676684
for error in PEP257Checker().check_source(source, filename):
677685
code = getattr(error, 'code', None)

test_pep257.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def test_ignore_list():
8282
expected_error_codes = set(('D100', 'D400', 'D401', 'D205', 'D209',
8383
'D210'))
8484
mock_open = mock.mock_open(read_data=function_to_check)
85-
with mock.patch('pep257.open', mock_open, create=True):
85+
with mock.patch('pep257.tokenize_open', mock_open, create=True):
8686
errors = tuple(pep257.check(['filepath']))
8787
error_codes = set(error.code for error in errors)
8888
assert error_codes == expected_error_codes

tox.ini

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
envlist = py26, py27, py32, py33, py34, pypy, pypy3
88

99
[testenv]
10+
# Make sure reading the UTF-8 from test.py works regardless of the locale used.
11+
setenv = LANG=C LC_ALL=C
1012
commands = py.test --pep8 --clearcache
1113
deps = pytest
1214
pytest-pep8

0 commit comments

Comments
 (0)