-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
PdfWriter.write() in context manager closes stream when it should not #2905
Comments
Thanks for the report. Feel free to submit a corresponding PR and test. |
I do not agree with your comment saying that the stream should not be closed : once you are calling
|
@pubpub-zz I think there are two arguments against keeping the current behavior.
I'd also counter the supposition that the stream is useless after |
I agree with @alexaryn in that responsibility of closing a stream should rest purely on the caller of Looking at the code, there is also the inefficiency where
I'm not sure what the correct behavior here should be, especially with regards to cloning. Like, if I call:
and |
@MasterOdin / @alexaryn, I've created a new issue with the @MasterOdin's last post as there is some issues there |
Calling
PdfWriter.write(fileobj)
unexpectedly closedfileobj
causing my program to crash later when it tried to dofileobj.seek(0)
.Environment
Which environment were you using when you encountered the problem?
Linux amd64; Python 3.11 and 3.12, but it doesn't matter, as it's a logic bug in the code.
Code
This code will trigger the issue with any PDF input:
After calling this,
out
is closed. It should not be.Traceback
n/a
Explanation
The problem arises here:
pypdf/pypdf/_writer.py
Line 1396 in dd39992
which seems like a special case for when
write()
is called from__exit__()
. However, just because thePdfWriter
was used in awith
...as
statement doesn't mean that the stream passed intowrite()
is the internalself.fileobj
. If it belongs to the caller, it should not be messed with.Potential Solution
Rather than closing in
write()
, why not close afterward in__exit__()
?Partial Workaround
write_stream()
does not have the problematic logic.The text was updated successfully, but these errors were encountered: