[issue33636] Unexpected behavior with * and arrays

Steven D'Aprano report at bugs.python.org
Thu May 24 13:54:17 EDT 2018


Steven D'Aprano <steve+python at pearwood.info> added the comment:

Nathan, the bug tracker is not the place to debate Python behaviour. For 
the purposes of the bug tracker, all we need say is that it is 
documented behaviour and not a bug. If you want to change that 
behaviour, there is a process to follow, and asking snarky questions on 
the tracker isn't part of it.

The principle of having multiple references to the same object is 
fundamental to Python, and very often useful. It's how objects are 
passed to functions, it is used for many forms of shared data. Your 
description of object sharing as "nonsense" and having no use-case is 
way off the mark.

But if it makes you feel better, the SPECIFIC example you ran into:

    [[]]*5  # makes 5 references to the same [] object

is rarely directly useful itself. It is certainly a "gotcha" that most 
Python programmers will stumble against at one time or another. But the 
behaviour follows from some fundamental designs of the language.

Copying objects is expensive, and often unnecessary. The Python 
interpreter does not automatically make copies of objects. The 
list.__mul__ method cannot know whether you require shallow copies, or 
deep copies, and for the majority of use-cases for list replication, 
copying would be unnecessary. So the * operator simply duplicates 
references. If you want copies, you have to copy the objects yourself.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33636>
_______________________________________


More information about the Python-bugs-list mailing list