Created
October 21, 2024 17:35
-
-
Save gilzoide/6c07993634f7a1c3c011b10a50cbf61f to your computer and use it in GitHub Desktop.
Deep copy implementation for Python with a fast path that uses `marshal`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
import marshal | |
def marshal_deepcopy(obj): | |
""" | |
Deep copy implementation that uses `marshal` for increased speed if possible, | |
falling back to `copy.deepcopy` if the passed object is not marshallable. | |
""" | |
try: | |
return marshal.loads(marshal.dumps(obj)) | |
except ValueError: | |
return copy.deepcopy(obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment