[Python-Dev] Re: switch statement

Nick Coghlan ncoghlan at gmail.com
Thu Apr 21 14:39:46 CEST 2005


Michael Chermside wrote:
> Now the pattern matching is more interesting, but again, I'd need to
> see a proposed syntax for Python before I could begin to consider it.
> If I understand it properly, pattern matching in Haskell relies
> primarily on Haskell's excellent typing system, which is absent in
> Python.

There's no real need for special syntax in Python - an appropriate tuple 
subclass will do the trick quite nicely:

class pattern(tuple):
   ignore = object()
   def __new__(cls, *args):
     return tuple.__new__(cls, args)
   def __hash__(self):
     raise NotImplementedError
   def __eq__(self, other):
     if len(self) != len(other):
         return False
     for item, other_item in zip(self, other):
       if item is pattern.ignore:
         continue
       if item != other_item:
         return False
     return True

Py> x = (1, 2, 3)
Py> print x == pattern(1, 2, 3)
True
Py> print x == pattern(1, pattern.ignore, pattern.ignore)
True
Py> print x == pattern(1, pattern.ignore, 3)
True
Py> print x == pattern(2, pattern.ignore, pattern.ignore)
False
Py> print x == pattern(1)
False

It's not usable in a dict-based switch statement, obviously, but it's perfectly 
compatible with the current if/elif idiom.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net


More information about the Python-Dev mailing list