[Python-ideas] Pattern matching

Chris Angelico rosuav at gmail.com
Wed Apr 8 06:56:45 CEST 2015


On Wed, Apr 8, 2015 at 12:45 PM, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Apr 7, 2015, at 19:04, Chris Angelico <rosuav at gmail.com> wrote:
>>
>> On Wed, Apr 8, 2015 at 7:10 AM, Andrew Barnert
>> <abarnert at yahoo.com.dmarc.invalid> wrote:
>>> The smaller problem is that in Python, only functions (and classes and modules) have scope; the idea of a name bound "locally" is tricky. There's a bit of hackery around except clauses...
>>
>> FWIW it's not hackery around scope at all - it's simply that the name
>> gets unbound:
>
> Sorry, you're right, "hackery" is misleading here; I should have just said "(yes, I know about comprehensions and except clauses, but they're not relevant here)" or something similar. I don't consider the 3.x rules for except "hacky" or bad in any way, and didn't mean to imply otherwise.
>

Gotcha.

> Anyway, an ML/Haskell case expression binds the matched variables inside the case branch; the most obvious interpretation of this proposal (or mine) would bind them in the entire function.
> Of course it's possible to solve that (if you think it needs solving) either the way comprehensions do (compile the case statement, or each branch, as a function definition and call) or the way except does (unbind names that appear in the "as" clause after the statement), or probably other ways, but if you don't do anything, they work like assignments. (Which is actually a perfectly good parallel to ML, where they work like let expressions, it's just that let expressions don't work like assignments.)
>

I'd treat these case branches like 'with' statements. The name binding
from "as" lasts past the end of the block, it's no different from any
other assignment. The only reason exceptions unbind is to avoid the
refloop of an exception having a reference to locals, and the local
name referencing the exception. Everything else can be just like
assignment.

So basically, what we have here is a cross between a 'with' statement
and an 'if'. I started writing up a demo that mainly used 'with', and
then realized that I had no idea how to have the __enter__ method
stipulate that the body should be skipped... oh, hello PEP 377, that's
where the problem is. This proposal would need some new syntax, but
conceptually, it'd be something like an __enter__ method returning
"hey, this body should be skipped", based on whatever criteria it
likes (isinstance, regex matching, etc).

ChrisA


More information about the Python-ideas mailing list