Skip to content

Instantly share code, notes, and snippets.

@gilzoide
Created October 21, 2024 17:35
Show Gist options
  • Save gilzoide/6c07993634f7a1c3c011b10a50cbf61f to your computer and use it in GitHub Desktop.
Save gilzoide/6c07993634f7a1c3c011b10a50cbf61f to your computer and use it in GitHub Desktop.
Deep copy implementation for Python with a fast path that uses `marshal`
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