[Python-ideas] Match statement brainstorm

Nick Coghlan ncoghlan at gmail.com
Wed May 25 01:52:50 EDT 2016


On 25 May 2016 at 15:11, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, May 25, 2016 at 3:03 PM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
>> How about
>>
>>     for <thing>:
>>         try <matcher>:
>>             pass
>>         try <matcher>:
>>             pass
>>
>> Look Ma!  No new keywords!  Yeah, I know, "for" and "try" both have
>> very strong connotations in Python already, so this may be a "not even
>> the Dutch could like it" automatic-parser-only syntax.
>
> I'd much prefer a different keyword instead of 'for'. If 'with' hadn't
> been used, that would be a better choice. Maybe 'using'... or
> 'switch'. But without iteration, 'for' is going to be very confusing.

As a variant on Guido's original switch/case idea:

    given EXPR [as TARGET]:
        case MATCH_PATTERN [as TARGET] [and CONDITION]:
            ...
        case MATCH_PATTERN [as TARGET] [and CONDITION]:
            ...
        case if CONDITION:
            ...
        case MATCH_PATTERN [as TARGET]:
            ...
        else:
            ...

Using the running demo:

    def demo(arg):
        given arg:
            case x, y, *_: # Tuple matching (implicit name binding)
                ...
            case (.x, .y) as p, q: # Attribute matching
                ...
            case (["x"], ["y"]) as p, q: # Item matching
                ...
            case (.x) as p and isinstance(p, int): # Match + condition
                ...
            case if isinstance(arg, int): # Condition only
                ...
            else: # Default
                ...

The other key change there is introducing "as" to the individual cases
in order to be able to separate the match pattern definition from the
local name binding.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list