From cb27e843cc1ba6151098a038d4b5a85e9516150d Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 14:52:10 +0000 Subject: [PATCH] Backport fix from PR #533. [ci skip] --- src/sire/_pythonize.py | 28 ++++++++++++++++++++++++++++ tests/base/test_deepcopy.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/base/test_deepcopy.py diff --git a/src/sire/_pythonize.py b/src/sire/_pythonize.py index 5f637a24e..1c067aec6 100644 --- a/src/sire/_pythonize.py +++ b/src/sire/_pythonize.py @@ -21,6 +21,27 @@ def _upper_split(data): yield buff +def _deepcopy(self, memo): + """ + Deep copy a wrapped object, which is the same as a copy since these + objects copy by value. + """ + return self.__copy__() + + +def _fix_deepcopy(C) -> None: + """ + Make copy.deepcopy work for a wrapped class. The generated wrappers bind + __deepcopy__ to the one-argument __copy__, but copy.deepcopy also passes + a memo dictionary. + """ + if hasattr(C, "__copy__"): + try: + C.__deepcopy__ = _deepcopy + except Exception: + pass + + def _pythonize(C, delete_old: bool = True) -> None: """Pythonize the passed class. This will rename the functions so that they better match the Python style @@ -51,6 +72,8 @@ def _pythonize(C, delete_old: bool = True) -> None: _pythonize(CLS) return + _fix_deepcopy(C) + import re for attr in dir(C): @@ -250,6 +273,11 @@ def _load_new_api_modules(delete_old: bool = True, is_base: bool = False): _pythonize(Convert._SireOpenMM.TorchQMEngine, delete_old=delete_old) _pythonize(Convert._SireOpenMM.TorchQMForce, delete_old=delete_old) + import inspect + + for _, cls in inspect.getmembers(Convert._SireOpenMM, inspect.isclass): + _fix_deepcopy(cls) + from ._lazy_import import force_load # Now make sure that all new modules have been loaded diff --git a/tests/base/test_deepcopy.py b/tests/base/test_deepcopy.py new file mode 100644 index 000000000..fc9be8d07 --- /dev/null +++ b/tests/base/test_deepcopy.py @@ -0,0 +1,34 @@ +import copy + +import pytest + + +@pytest.mark.parametrize( + "create", + [ + lambda sr: sr.u("1 ps"), + lambda sr: sr.legacy.Mol.AtomIdx(3), + lambda sr: sr.cas.LambdaSchedule.standard_morph(), + ], +) +def test_deepcopy(create): + import sire as sr + + obj = create(sr) + other = copy.deepcopy(obj) + assert other == obj + assert other is not obj + + +def test_deepcopy_openmm(): + from sire.legacy.Convert import _SireOpenMM + + lever = _SireOpenMM.LambdaLever() + assert copy.deepcopy(lever) is not lever + + +def test_deepcopy_container(): + import sire as sr + + d = {"time": sr.u("2 ps"), "atoms": [sr.legacy.Mol.AtomIdx(1)]} + assert copy.deepcopy(d) == d