inline comparison

Diez B. Roggisch deetsNOSPAM at
Sun Mar 20 16:47:48 CET 2005

> This is very bad to me, I will need to write some cumbersome syntax as
> follow:
>         for d in
>              m = self.macro_parser.match (d)) != None ):
>              if (m == None):
>                 m_nat = self.a_parser.match (d)
>                 if (m_a == None):
>                    m_rdr = self.b_parser.match (d)
>                    if (m_b == None):
>                        m_c = self.c_parser.match (d)
>                        if (m_c == None):
>                           m_d = self.d_parser.match (d)
>                           if (m_d == None):
>                              m_e = self.e_parser.match (d)
>                              if (m_e == None):
>   .....

This has been discussed a zillion times on - and various solutions
have been suggested, amongst these is something like this:

class Matcher:
    def __init__(self, rex):
        self.rex = rex

    def match(self, data): = self.rex.match(data)

Then you can use code like this:

m  = Matcher(...)

if m.match("some string"):

And beside that: the code you gave above does _not_ look better if you could
inline the assignment, you still have the same hierarchy of if-statements.

If you really need that sort of dependent matching, there are better ways to
accomplish that in python:

for m, name in [self.macro_parser, self.a_parser, self.b_parser, ...]:
    mo = m.match(data)
    if mo:


Diez B. Roggisch

More information about the Python-list mailing list