MCPcopy
hub / github.com/pydantic/pydantic / smart_deepcopy

Function smart_deepcopy

pydantic/v1/utils.py:676–694  ·  view source on GitHub ↗

Return type as is for immutable built-in types Use obj.copy() for built-in empty collections Use copy.deepcopy() for non-empty collections and unknown objects

(obj: Obj)

Source from the content-addressed store, hash-verified

674
675
676def smart_deepcopy(obj: Obj) -> Obj:
677 """
678 Return type as is for immutable built-in types
679 Use obj.copy() for built-in empty collections
680 Use copy.deepcopy() for non-empty collections and unknown objects
681 """
682
683 obj_type = obj.__class__
684 if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES:
685 return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway
686 try:
687 if not obj and obj_type in BUILTIN_COLLECTIONS:
688 # faster way for empty collections, no need to copy its members
689 return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method
690 except (TypeError, ValueError, RuntimeError):
691 # do we really dare to catch ALL errors? Seems a bit risky
692 pass
693
694 return deepcopy(obj) # slowest way when we actually might need a deepcopy
695
696
697def is_valid_field(name: str) -> bool:

Callers 3

get_defaultMethod · 0.90
get_defaultMethod · 0.90
__new__Method · 0.90

Calls 1

copyMethod · 0.45

Tested by

no test coverage detected