pyjson5 icon indicating copy to clipboard operation
pyjson5 copied to clipboard

cannot load file directly without reading into string first

Open garfieldnate opened this issue 8 months ago • 2 comments

This might just be a typing error. I can use the built-in json module to parse a file directly like so:

import json

filename = "/path/to/file"
with open(filename, 'r') as f:
    document = json.load(f)

However, if I replace the import line with import pyjson5 as json, I get this typing error:

Argument of type "TextIOWrapper[_WrappedBuffer]" cannot be assigned to parameter "fp" of type "_SupportsRead" in function "load"
  "TextIOWrapper[_WrappedBuffer]" is incompatible with protocol "_SupportsRead"
    "read" is an incompatible type
      Type "(size: int | None = -1, /) -> str" is not assignable to type "(size: int = ...) -> str"
        Missing keyword parameter "size"
          Position-only parameter mismatch; parameter "size" is not position-only

This seems to suggest that I'm supposed to read the file into a string before parsing it, which is not ideal given that it might be a large file, as well as creating friction when trying to migrate from json to pyjson5.

garfieldnate avatar Jun 04 '25 17:06 garfieldnate

Thank you for reporting the error!

Yes, this is only a typing problem: https://github.com/Kijewski/pyjson5/blob/c0cc1cd0d845a82328f022a4ec21f81a5db0cbef/src/pyjson5/__init__.pyi#L18-L19 This should be:

class _SupportsRead(Protocol):
    def read(self, size: int | None = ...) -> str | bytes: ...

Kijewski avatar Jun 04 '25 17:06 Kijewski

I thought it might be :D I was looking at the documentation just now thinking, "I swear this is supported...". Thanks for the quick response!

garfieldnate avatar Jun 04 '25 17:06 garfieldnate

Thank you again for the bug report! :) Fixed in v2.0.0.

Kijewski avatar Oct 02 '25 00:10 Kijewski