简体   繁体   中英

Does `copy.deepcopy` work with `NamedTuple`s in Python?

I see in the documentation that there's a __deepcopy__ method that can be used to extend the behavior of deepcopy beyond the built-in types. However, the documentation for NamedTuple (the class version in the typing module) doesn't mention anything about it. But since it provides defaults for hashing and equality testing, I was wondering, does it provide a default for deep copying as well?

NamedTuple doesn't define a special __deepcopy__ handler, but it doesn't need to. __deepcopy__ is only necessary to override/customize the default deep copying behavior (which just uses the pickle special methods, __reduce_ex__ or __reduce__ ); for classes defined in Python (as opposed to C extension types), the default behavior is generally correct/complete. object itself provides useful default pickling behaviors for all non-extension types, assuming all their attributes are themselves picklable, eg no open file objects or the like.

Since NamedTuple is Python level, and has no special copying needs, it doesn't bother to implement a custom handler. You'd need to do so yourself only if some of the attributes of your NamedTuple are unpicklable and don't themselves define __deepcopy__ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM