[Python-ideas] Pattern Matching Syntax

Robert Roskam raiderrobert at gmail.com
Thu May 3 15:02:47 EDT 2018


Hey Chris,

Thanks for bringing that up! Before submitting this, I actually had the 
syntax for multiple matches for one arm being separated by or. And frankly 
I just didn't like how that looked for more than 3 items:

'1' or '2' or '3' or '4' or '5' vs  '1', '2', '3', '4', '5'

But you're right. The syntax should be for tuples instead.


Here's my revised syntax, using a guard instead for the moment:

def convert_time_to_timedelta_with_match(unit:str, amount:int, now:date):
 return match unit:
     x if x in ('days', 'hours', 'weeks') => timedelta(**{unit: amount})
     'months' => timedelta(days=30 * amount)
     'years' => timedelta(days=365 * amount)
     'cal_years' => now - now.replace(year=now.year - amount)



On Thursday, May 3, 2018 at 2:54:24 PM UTC-4, Chris Angelico wrote:
>
> On Fri, May 4, 2018 at 4:36 AM, Robert Roskam <raider... at gmail.com 
> <javascript:>> wrote: 
> > Hey Chris, 
> > 
> > So I started extremely generally with my syntax, but it seems like I 
> should 
> > provide a lot more examples of real use. Examples are hard. Here's my 
> > hastily put together example from an existing piece of production code: 
> > 
> > 
> > # New Syntax for same problem 
> > 
> > 
> > def convert_time_to_timedelta_with_match(unit:str, amount:int, 
> now:date): 
> >  return match unit: 
> >      'days', 'hours', 'weeks' => timedelta(**{unit: amount}) 
> >      'months' => timedelta(days=30 * amount) 
> >      'years' => timedelta(days=365 * amount) 
> >      'cal_years' => now - now.replace(year=now.year - amount) 
>
> Okay, here we may have a problem. You're expecting a comma separated 
> set of values to indicate "any of these", but elsewhere, pattern 
> matching against a list of values is making an assertion about a 
> tuple. So if you have any pattern matching that isn't based on 
> equality, you're going to need to clearly stipulate how your syntax 
> works. 
>
> If you are NOT going to support tuple pattern matching (but only 
> dict), you'll need to make this VERY clear, because people are going 
> to expect it. 
>
> ChrisA 
> _______________________________________________ 
> Python-ideas mailing list 
> Python... at python.org <javascript:> 
> https://mail.python.org/mailman/listinfo/python-ideas 
> Code of Conduct: http://python.org/psf/codeofconduct/ 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180503/50557b4b/attachment-0001.html>


More information about the Python-ideas mailing list