Skip to content

Commit

Permalink
Merge pull request #1232 from mbway/pickle_support
Browse files Browse the repository at this point in the history
add support for pickling DXF entities
  • Loading branch information
mozman authored Jan 23, 2025
2 parents ad66c16 + 2e3801d commit 53ef743
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/ezdxf/entities/dxfns.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ def copy(self, entity: DXFEntity):
def __deepcopy__(self, memodict: Optional[dict] = None):
return self.copy(self._entity)

def __getstate__(self) -> object:
return self.__dict__

def __setstate__(self, state: object) -> None:
if not isinstance(state, dict):
raise TypeError(f"invalid state: {type(state).__name__}")
# bypass __setattr__
object.__setattr__(self, "__dict__", state)

def reset_handles(self):
"""Reset handle and owner to None."""
self.__dict__["handle"] = None
Expand Down
36 changes: 36 additions & 0 deletions tests/test_10_issues/test_issue_1231_pickling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import io
import pickle
from collections.abc import Iterator
from pathlib import Path

import pytest

import ezdxf
from ezdxf.document import Drawing

EXAMPLES = Path(__file__).parent.parent.parent / "examples_dxf"


def example_dxfs() -> Iterator[Path]:
for item in EXAMPLES.iterdir():
if item.suffix.lower() == ".dxf":
yield item


def _to_dxf_str(doc: Drawing) -> str:
stream = io.StringIO()
doc.write(stream)
return stream.getvalue()


def test_document_pickle(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(ezdxf.options, "write_fixed_meta_data_for_testing", True)

for item in example_dxfs():
print(f"testing pickling of {item}")

doc = ezdxf.readfile(item)
doc_serialized = pickle.dumps(doc)
doc_loaded = pickle.loads(doc_serialized)

assert _to_dxf_str(doc) == _to_dxf_str(doc_loaded)

0 comments on commit 53ef743

Please sign in to comment.