Skip to content

Fix AttributeError when encoding detection returns None #304

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ htmlcov/
.idea/
.vscode/
.tox/
.venv/
12 changes: 9 additions & 3 deletions src/docformatter/encode.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,12 @@ class Encoder:
LF = "\n"
CRLF = "\r\n"

# Default encoding to use if the file encoding cannot be detected
DEFAULT_ENCODING = "latin-1"

def __init__(self):
"""Initialize an Encoder instance."""
self.encoding = "latin-1"
self.encoding = self.DEFAULT_ENCODING
self.system_encoding = locale.getpreferredencoding() or sys.getdefaultencoding()

def do_detect_encoding(self, filename) -> None:
Expand All @@ -56,13 +59,16 @@ def do_detect_encoding(self, filename) -> None:
The full path name of the file whose encoding is to be detected.
"""
try:
self.encoding = from_path(filename).best().encoding
detection_result = from_path(filename).best()
self.encoding = (
detection_result.encoding if detection_result else self.DEFAULT_ENCODING
)

# Check for correctness of encoding.
with self.do_open_with_encoding(filename) as check_file:
check_file.read()
except (SyntaxError, LookupError, UnicodeDecodeError):
self.encoding = "latin-1"
self.encoding = self.DEFAULT_ENCODING

def do_find_newline(self, source: List[str]) -> str:
"""Return type of newline used in source.
Expand Down
15 changes: 15 additions & 0 deletions tests/test_encoding_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,21 @@ def test_detect_encoding_with_bad_encoding(self, temporary_file, contents):

assert "ascii" == uut.encoding

@pytest.mark.unit
@pytest.mark.parametrize("contents", [""])
def test_detect_encoding_with_undetectable_encoding(self, temporary_file):
"""Default to latin-1 when encoding detection fails."""
uut = Encoder()

# Simulate a file with undetectable encoding
with open(temporary_file, "wb") as file:
# Binary content unlikely to have a detectable encoding
file.write(b"\xFF\xFE\xFD\xFC\x00\x00\x00\x00")

uut.do_detect_encoding(temporary_file)

assert uut.encoding == uut.DEFAULT_ENCODING


class TestFindNewline:
"""Class for testing the find_newline() function."""
Expand Down
Loading