Skip to content

Ability to ignore unidcode decode errors. #1443

Open

Description

@andredriem

I ran on a issue today where I as trying to read a File object from a malformed utf-8 string with an invalid character. I managed to fix my issue creating my own readlines() function with a try/catch block, but I don't think this solution is resistant to future updates from this libary since I cant' guarantee that the file cursor will move to the next line before this error occur.

def readlines(file):
  lines = []
  eof = False
  while not eof:
    try:
      line = file.readline()
      if line == '':
        eof = True
      else:
        lines.append(line)
    except UnicodeDecodeError as e:
      lines.append(e.object.decode('utf-8',errors='replace'))
  return lines

One simple solution to this would be adding a default error handling in line 68.

def u(s, encoding="utf8"): # NOQA
"""cast bytes or unicode to unicode"""
if isinstance(s, str):
return s.decode(encoding)
elif isinstance(s, unicode): # NOQA
return s
elif isinstance(s, buffer): # NOQA
return s.decode(encoding)
else:
raise TypeError("Expected unicode or bytes, got {!r}".format(s))

changing to

return s.decode(encoding, errors='replace')

or even better giving the user the choice of how she/he would handle the errors via an optional argument.

Activity

  1. changed the title [-]Hability to ignore unidcode decode errors.[/-] [+]Ability to ignore unidcode decode errors.[/+] on May 11, 2019
  2. hakaishi commented on Mar 14, 2022

    @hakaishi

    continuation of previous pull request at #1995

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions