Mark PyEncoder as frozen and use interior mutability #1860
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I'm opening this to see what the maintainer's appetite is for this sort of change.
I'm particularly curious if the maintainers are OK with the change to migrate from
__getstate__
and__setstate__
to use__getnewargs__
. The latter doesn't require a&mut self
reference. I had to add an optional bytes argument to__new__
, which seemed like it would be fine but I guess technically it is a public API change.See https://pyo3.rs/v0.26.0/class.html#frozen-classes-opting-out-of-interior-mutability for more about this. In the future it's likely that PyO3 will make frozen pyclasses the default.
From the perspective of multithreaded use and the free-threaded build, this change makes it impossible for people to see runtime borrow-checker errors if two threads race to mutate and read the state of a PyEncoder, or a single thread tries to mutably borrow a PyEncoder twice. The latter is no longer a problem because it's no longer possible to mutably borrow
PyEncoder
. It's still possible to mutate the internal state, but all state is synchronized (in the sense ofSend
andSync
) by the mutex.