Note that there are some explanatory texts on larger screens.

plurals
  1. POPlease explain reasoning behind code snippet from argparse module
    text
    copied!<p>I was looking at the source code for the built-in <a href="http://docs.python.org/2/library/argparse.html#action" rel="nofollow noreferrer">argparse._AppendAction</a>, which implements the <code>"append"</code> action, and puzzled over the <a href="http://hg.python.org/cpython/file/1f66fc397c8d/Lib/argparse.py#l946" rel="nofollow noreferrer">way it is implemented</a>:</p> <pre><code> def __call__(self, parser, namespace, values, option_string=None): items = _copy.copy(_ensure_value(namespace, self.dest, [])) items.append(values) setattr(namespace, self.dest, items) </code></pre> <p>To break it down:</p> <ul> <li><code>_ensure_value</code> is like <code>dict.setdefault</code> for attributes. That is, if <code>namespace</code> has an attribute with the name <code>self.dest</code> then it is returned, if not it is set to <code>[]</code> and returned.</li> <li><code>_copy.copy(x)</code> returns just a shallow copy. When <code>x</code> is a list it is exactly like <code>list(x)</code> (but slower).</li> <li>Then the item is appended to the <em>copy</em> of the list gotten from <code>namespace</code>.</li> <li>Finally the <code>self.dest</code> attribute of <code>namespace</code> is overwritten with the copy, which should cause the old list to be garbage collected.</li> </ul> <p>Why do it in such a roundabout and inefficient way, throwing away a whole list for each append? Why doesn't this suffice?</p> <pre><code> def __call__(self, parser, namespace, values, option_string=None): items = _ensure_value(namespace, self.dest, []) items.append(values) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload