From 9191fccd3a83fcac1f1154b8cb8c756f36897144 Mon Sep 17 00:00:00 2001 From: Erfouni Date: Thu, 8 Oct 2026 23:53:32 +0330 Subject: [PATCH] Raise PlyHeaderParseError, not UnicodeDecodeError, on a non-ASCII header _PlyHeaderLines._decode did a strict s.decode('ascii'), so reading a file whose first bytes are not ASCII (e.g. a PNG or other binary passed by mistake) raised a bare UnicodeDecodeError instead of the PlyHeaderParseError that a non-PLY ASCII file already gives. Catch UnicodeDecodeError in _decode and raise PlyHeaderParseError, which also covers non-ASCII bytes later in the header. Added a test. --- plyfile.py | 6 +++++- test/test_plyfile.py | 7 +++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/plyfile.py b/plyfile.py index c2a1e1d..6e4fa52 100644 --- a/plyfile.py +++ b/plyfile.py @@ -1298,7 +1298,11 @@ def _decode(s): """ if isinstance(s, str): return s - return s.decode('ascii') + try: + return s.decode('ascii') + except UnicodeDecodeError: + raise PlyHeaderParseError( + "header contains non-ASCII characters") def __iter__(self): """ diff --git a/test/test_plyfile.py b/test/test_plyfile.py index cf15d46..2930796 100644 --- a/test/test_plyfile.py +++ b/test/test_plyfile.py @@ -802,6 +802,13 @@ def test_header_parse_error(s, line): assert e.exc_val.line == line +def test_header_non_ascii_bytes(): + # a non-PLY binary file (e.g. a PNG) should raise PlyHeaderParseError, + # not a raw UnicodeDecodeError from the non-ASCII header bytes + with Raises(PlyHeaderParseError): + PlyData.read(BytesIO(b'\x89PNG\r\n\x1a\n' + b'\x00' * 40)) + + invalid_arrays = [ numpy.zeros((2, 2)), numpy.array([(0, (0, 0))],