List replication operator
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 25 02:42:43 EDT 2018
On Fri, 25 May 2018 08:11:52 +0200, Stefan Behnel wrote:
> Steven D'Aprano schrieb am 25.05.2018 um 04:25:
[...]
>> You might be right: on further thought, I think I want deep copies, not
>> shallow.
>
> But how would that protocol work then? What would happen with a data
> structure like this:
>
> [( 1, [1, 2, 3] )] ** 3
>
> ? Would it also deep copy the tuple, or ignore it?
It would deep-copy the items. It would do whatever copy.deepcopy() does,
which is deep-copy the object *all the way down*.
> What about other, non-builtin sequence types?
I've concentrated on lists because that's usually the sequence type used.
Adding ** (or @ if you prefer) could be made part of the sequence API if
needed, but I'd be happy to start with lists and see if there is a demand
to add it to other objects as well.
> The '**' operator cannot just recursively
> call '**' on the items in the list, because they may not support it. Or
> they may support it, but not in the expected way.
Nobody is talking about calling ** recursively.
I gave a simple implementation. No recursion is needed, except inside
deepcopy, which is already a solved problem.
> And limiting this to lists of lists seems rather arbitrary. What about
> subtypes of lists?
Perhaps you have heard of inheritance? If lists support this, their
subclasses will automatically support it too, unless you override the
relevant methods.
> Calling "copy.deepcopy()" internally instead of a recursive '**' doesn't
> seem safe either, because it also wouldn't know where to stop.
Of course it does. It stops when it has copied everything, all the way
down. That's what it does.
--
Steve
More information about the Python-list
mailing list