unified-font-object / ufoLib

A low-level UFO reader and writer.
Other
37 stars 19 forks source link

writeBytesToPath() fails when encoding is specified #168

Closed khaledhosny closed 6 years ago

khaledhosny commented 6 years ago

The following code:

from ufoLib import UFOWriter

w = UFOWriter("test.ufo")
w.writeBytesToPath("data/test", u"foo", encoding="utf-8")

Fails with the following error:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    w.writeBytesToPath("data/test", u"foo", encoding="utf-8")
  File "/usr/lib/python3.7/site-packages/ufoLib/__init__.py", line 789, in writeBytesToPath
    data = StringIO(data).encode(encoding)
AttributeError: '_io.StringIO' object has no attribute 'encode'
anthrotype commented 6 years ago

that's wrong, indeed. It should be changed to tobytes(data, encoding=encoding) However, if the method is called writeBytesToPath, it would also be correct to expect that data is of type bytes already and raise if it isn't, passing responsibility of encoding it to the caller. @khaledhosny can you send a PR?

anthrotype commented 6 years ago

UFOWriter.writeBytesToPath doesn't have an encoding argument any more, because it didn't make any sense. The method says "write bytes" so the user should pass a string of type bytes. If it were named "write text" then the encoding argument would have made sense: it would mean, use this encoding to convert some text (a unicode string) to bytes when writing the file.

it's the same reason that built-in open function doesn't accept an encoding parameter when the mode is wb.