Stream: helpdesk (published)

Topic: iswritable


view this post on Zulip Fredrik Ekre (Jan 29 2021 at 14:48):

What does iswritable(io) actually mean? I thought it would mean it would accept write(io, stuf...) but apparently not?

julia> f = open("tmp", "w");

julia> iswritable(f)
true

julia> write(f, "hi")
2

julia> close(f)

julia> iswritable(f)
true

julia> write(f, "hi")
0

view this post on Zulip Fredrik Ekre (Jan 29 2021 at 14:55):

Should I check isopen and iswritable maybe?

view this post on Zulip Sebastian Pfitzner (Jan 29 2021 at 14:58):

yes, I think so

view this post on Zulip Sebastian Pfitzner (Jan 29 2021 at 14:58):

iswritable checks whether your io is readonly or not:

julia> io = IOBuffer("asd")
IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=3, maxsize=Inf, ptr=1, mark=-1)

julia> iswritable(io)
false

julia> write(io, "asd")
ERROR: ArgumentError: ensureroom failed, IOBuffer is not writeable

view this post on Zulip Fredrik Ekre (Jan 29 2021 at 15:05):

Right. I thought that iswritable would imply isopen.

view this post on Zulip Fredrik Ekre (Jan 30 2021 at 13:22):

It seems that many streams don't define iswritable so it looks like the most fail-safe way is to just try. And since e.g. IOStream does not even throw

julia> io = open("test.txt", "w")
       close(io)
       write(io, "hello")
0

it looks like you have to verify that the number of written bytes is what you expect? Something like

julia> io = open("test.txt", "w")
       close(io)
       txt = "hello"
       nb = sizeof(txt)
       n = write(io, txt)
       if n != nb
           error("could not write")
       end
ERROR: could not write
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] top-level scope
   @ REPL[3]:7

view this post on Zulip Fredrik Ekre (Jan 30 2021 at 13:41):

What is the benefit of write not throwing and instead returning 0 here?

view this post on Zulip Fredrik Ekre (Jan 30 2021 at 13:45):

It seems inconsistent that if the stream is not writable it throws but if it is closed it returns 0. Why not either return 0 in both cases or throw in both cases?

view this post on Zulip Fredrik Ekre (Jan 30 2021 at 13:57):

Python throws:

>>> with open("file.txt", "w") as io:
...     io.write("hello")
...     io.close()
...     io.write("world")
...
5
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: I/O operation on closed file.

view this post on Zulip Florian Große (Jan 30 2021 at 15:05):

Well spotted:point_up: maybe there's a conclusive reason for that, but I'd definitely expect it to throw, too

view this post on Zulip Fredrik Ekre (Jan 30 2021 at 15:15):

https://github.com/JuliaLang/julia/issues/1701 seems to suggest it is intentional and https://linux.die.net/man/2/write says up to n bytes.


Last updated: Oct 02 2023 at 04:34 UTC