[Python-ideas] Match statement brainstorm
Michael Selik
michael.selik at gmail.com
Fri May 20 12:03:50 EDT 2016
On Thu, May 19, 2016 at 10:38 PM Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 19 May 2016 at 14:15, Guido van Rossum <guido at python.org> wrote:
> > The attribute idea would be similar to a duck-type check, though more
> > emphasizing data attributes. It would be nice if we could write a
> > match that said "if it has attributes x and y, assign those to local
> > variables p and q, and ignore other attributes".
>
> If we went down that path, then the "assign if you can, execute this
> case if you succeed" options would presumably need an explicit prefix
> to indicate they're not normal expressions, perhaps something like
> "?=":
>
> switch expr as arg:
> case ?= (.x as p, .y as q): print('x=', p, 'y=', q)
>
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:
def foo(obj):
return a ?= obj.a
Could be equivalent to:
def foo(obj):
try:
a = obj.a
except Exception:
return False
else:
return True
The use-cases of are somewhat overlapping with the idea of an inline
try/except as in PEP 463 (https://www.python.org/dev/peps/pep-0463/).
Which would then have the further implication that it might also make
> sense to support attribute unpacking as the LHS of normal assignment
> statements:
>
> (.x as p, .y as q) = expr
>
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:
o = expr
p, q = o.x, o.y
Using a temporary variable like ``o`` makes it even fewer characters than
the proposed parens and ``as`` keyword.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160520/f3ca17a4/attachment.html>
More information about the Python-ideas
mailing list