<div dir="ltr"><div class="gmail_quote"><div dir="ltr">On Thu, May 19, 2016 at 10:38 PM Nick Coghlan <<a href="mailto:ncoghlan@gmail.com">ncoghlan@gmail.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On 19 May 2016 at 14:15, Guido van Rossum <<a href="mailto:guido@python.org" target="_blank">guido@python.org</a>> wrote:<br>
> The attribute idea would be similar to a duck-type check, though more<br>
> emphasizing data attributes. It would be nice if we could write a<br>
> match that said "if it has attributes x and y, assign those to local<br>
> variables p and q, and ignore other attributes".<br></blockquote><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
If we went down that path, then the "assign if you can, execute this<br>
case if you succeed" options would presumably need an explicit prefix<br>
to indicate they're not normal expressions, perhaps something like<br>
"?=":<br>
<br>
switch expr as arg:<br>
case ?= (.x as p, .y as q): print('x=', p, 'y=', q)<br></blockquote><div><div><span style="line-height:1.5"><br class="inbox-inbox-Apple-interchange-newline">If you don't mind adding a new operator, then an easier way to handle several of these situations would be to make ``?=`` an assignment expression that evaluates to True/False whether the assignment succeeded:</span><br></div><div><span style="line-height:1.5"><br></span></div><div><div> def foo(obj):</div><div> return a ?= obj.a</div></div><div><span style="line-height:1.5"><br></span></div><div><span style="line-height:1.5">Could be equivalent to:</span></div><div><span style="line-height:1.5"><br></span></div><div><div> def foo(obj):</div><div> try:</div><div> a = obj.a</div><div> except Exception:</div><div> return False</div><div> else:</div><div> return True</div></div></div><div><br></div><div><br></div><div>The use-cases of are somewhat overlapping with the idea of an inline try/except as in PEP 463 (<a href="https://www.python.org/dev/peps/pep-0463/">https://www.python.org/dev/peps/pep-0463/</a>).<br></div><div><br></div><div><br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Which would then have the further implication that it might also make<br>
sense to support attribute unpacking as the LHS of normal assignment<br>
statements:<br>
<br>
(.x as p, .y as q) = expr<br></blockquote><div><br></div><div>The ``as`` syntax flips the familiar variable-on-the-left and makes this one tough for me to read. I'd rather force a little repetition:</div><div><br></div><div> o = expr</div><div> p, q = o.x, o.y</div><div><br></div><div>Using a temporary variable like ``o`` makes it even fewer characters than the proposed parens and ``as`` keyword.</div></div></div>