
On Wed, Feb 10, 2010 at 12:10 PM, Raymond Hettinger <raymond.hettinger@gmail.com> wrote:
On Feb 10, 2010, at 6:54 AM, Gerald Britton wrote:
Yes, I plan to ask for copy() as well, when the bug tracker opens up for 3.3, 3.4, etc. The issue is not, "Is there already a way to do this?" but rather, "Can we have consistent interfaces in the sequence types and collections where possible and appropriate?"
Use the copy module.
dict() and set() already support both clear() and copy() methods. Previous posters have pointed to the disconnect and showed the problem of having to test if a given iterable supports the clear() method before calling it, in functions that take any iterable.
Also, for what it's worth:
s1 = set() s2 = s1.copy()
is faster than
s1 = set() s2 = set(s1)
I question your timing skills. Both call the same routine to do the work of copying entries:
set_copy() calls make_new_set() which calls set_update_internal() set_init() calls set_update_internal()
If there is any difference at all, it is the constant overhead of passing an argument to set(), not the implementation itself. The actual set building work is the same.
(and also for dict()) probably because the first is specifically-written for the copy operation whereas the second actually iterates over s1, one item at a time. (At least I think that's what's going on). I suppose that a list().copy() method might also be faster than the other two approaches to copy a list.
You need to read some code, learn about ref counts, etc. There's more to list copying than a memcpy(). If list.copy() were added, it would use that same underlying code as list(s) and s[:]. There would be no speed-up.
Lastly, for completeness, I suppose copy() might be appropriate for both tuple and deque as well.
Tuples? Really? An immutable collection is its own copy.
Raymond
Thanks for the feedback. I also question my timing skills (and most other skills that I think I have). That's what's good about bouncing ideas around here. Silly ones get shot down, and rightly so! -- Gerald Britton