[Python-ideas] Pattern Matching Syntax

Chris Angelico rosuav at gmail.com
Thu May 3 14:53:27 EDT 2018

On Fri, May 4, 2018 at 4:36 AM, Robert Roskam <raiderrobert at gmail.com> 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

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.


More information about the Python-ideas mailing list