[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:
       if item != other_item:
         return False
     return True

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

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


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

More information about the Python-Dev mailing list