Josh Rosenberg <shadowranger+pyt...@gmail.com> added the comment:

If you're annoyed by having to use two lines, one to copy, one to call the 
mutating method, you can use the walrus operator:

(y := x.copy()).some_method()

or:

(y := deepcopy(x)).some_method()

Does that cover your use case?

For the list case, you'd normally just do:

arr = lis[::-1]

but:

(arr = lis.copy()).reverse()

also works.

Granted, not super pretty. But I'm not seeing enough cases where this ugliness 
is truly unavoidable (the two lines don't bother me that much, and for 
built-ins, there is usually a one-liner that works fine, e.g. the reversing 
slice as shown, sorted over list.sort, etc.).

I'll note: Unconditionally calling copy.copy is fine; it knows to try the 
__copy__ method of the things it is called on (and most things that offer copy 
alias it to __copy__ or are special-cased in copy.copy as well; if they don't, 
they should), so you're unlikely to need to perform the "try method, fall back 
to copy.copy" yourself.

----------
nosy: +josh.r

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42646>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to