Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> but rather, you should do > magic = f.read(4) > assert magic == b"\x89PNG", "Not a PNG file"

If the `assert` compiles out, wouldn’t -O also possibly compile the `read()` out as well given `magic` isn’t used after the assign?



No. Ignoring that Python does not have anywhere near this level of optimisation, read() has side effects so optimising it away would be broken in the general case.

It could be optimised away if all following uses would invalidate (seek, but only with SEEK_SET or SEEK_END) or ignore (pread/pwrite) the file offset, but that seems like an enormous amount of fussy work for what I would guess is little to no payback.


Ah side effects, which Python doesn’t track anyway. Thanks


I don't know the Python rules for thus but the way I understand it from C and C++ is that the read can't be removed by the optimizer because it has (or rather is considered to have) side effects. Iirc every syscall falls into this category.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: