typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Opaque type for io.TextIOWrapper seek and tell?

Open Akuli opened this issue 3 years ago • 1 comments

The following prints 18446744073709551620 (as I discovered in https://github.com/python/cpython/issues/93077):

import io
stream = io.TextIOWrapper(io.BytesIO(b'"")\r\nx\r\n'))
stream.read(1)
stream.read(1)
stream.read(1)
print('-----> tell:', stream.tell())

This is not a bug. The documentation says that .tell() returns "an opaque number" that "does not usually represent a number of bytes in the underlying binary storage".

In fact, calling .seek() with anything else than 0 or a return value of .tell() "produces undefined behaviour". I just relied on that today, without knowing it. I wrote this code:

def _upgrade_high_scores_file(file: IO[str], old_version: int) -> None:
    ...
    file.seek(len(b"catris high scores file v"))
    ...

This shouldn't pass the type check IMO.

Akuli avatar May 22 '22 20:05 Akuli

We could experiment with NewType here and see what primer says.

srittau avatar May 27 '22 10:05 srittau