Skip to content

Instantly share code, notes, and snippets.

@1ort
Last active May 27, 2024 13:07
Show Gist options
  • Save 1ort/4e9e8b1032d62ce5eb91607cd05d897f to your computer and use it in GitHub Desktop.
Save 1ort/4e9e8b1032d62ce5eb91607cd05d897f to your computer and use it in GitHub Desktop.
from dataclasses import dataclass
import pickle
import io
@dataclass(frozen=True)
class Foo:
x: int
@dataclass(frozen=True)
class Bar:
y: int
# initial write
with open('test.pickle', 'wb') as file:
foo = Foo(10)
pickle.dump(foo, file)
# assert write correct
with open('test.pickle', 'rb') as file:
foo = pickle.load(file)
assert isinstance(foo, Foo)
assert foo.x == 10
# rewrite with single descriptor. Watch here
with open('test.pickle', 'r+b') as file:
foo = pickle.load(file)
assert foo.x == 10
file.seek(0)
bar = Bar(25)
pickle.dump(bar, file)
# assert write correct
with open('test.pickle', 'rb') as file:
bar = pickle.load(file)
assert isinstance(bar, Bar)
assert bar.y == 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment