C-like assignment expression?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • boblatest@googlemail.com

    C-like assignment expression?

    Hello,

    I have an if-elif chain in which I'd like to match a string against
    several regular expressions. Also I'd like to use the match groups
    within the respective elif... block. The C-like idiom that I would
    like to use is this:

    if (match = my_re1.match(li ne):
    # use match
    elsif (match = my_re2.match(li ne)):
    # use match
    elsif (match = my_re3.match(li ne))
    # use match

    ....buy this is illegal in python. The other way is to open up an else:
    block in each level, do the assignment and then the test. This
    unneccessarily leads to deeper and deeper nesting levels which I find
    ugly. Just as ugly as first testing against the RE in the elif: clause
    and then, if it matches, to re-evaluate the RE to access the match
    groups.

    Thanks,
    robert
  • Diez B. Roggisch

    #2
    Re: C-like assignment expression?

    boblatest@googl email.com wrote:
    Hello,
    >
    I have an if-elif chain in which I'd like to match a string against
    several regular expressions. Also I'd like to use the match groups
    within the respective elif... block. The C-like idiom that I would
    like to use is this:
    >
    if (match = my_re1.match(li ne):
    # use match
    elsif (match = my_re2.match(li ne)):
    # use match
    elsif (match = my_re3.match(li ne))
    # use match
    >
    ...buy this is illegal in python. The other way is to open up an else:
    block in each level, do the assignment and then the test. This
    unneccessarily leads to deeper and deeper nesting levels which I find
    ugly. Just as ugly as first testing against the RE in the elif: clause
    and then, if it matches, to re-evaluate the RE to access the match
    groups.
    This might help:

    -----------
    s = "foo"

    class Tester(object):

    def __call__(self, pattern):
    self.m = re.match(patter n, s)
    return self.m is not None

    def __getattr__(sel f, name):
    return getattr(self.m, name)

    test = Tester()

    if test("bar"):
    print "wrong"
    elif test("foo"):
    print "right"
    -------------


    Diez

    Comment

    • Ulrich Eckhardt

      #3
      Re: C-like assignment expression?

      boblatest@googl email.com wrote:
      I have an if-elif chain in which I'd like to match a string against
      several regular expressions. Also I'd like to use the match groups
      within the respective elif... block. The C-like idiom that I would
      like to use is this:
      >
      if (match = my_re1.match(li ne):
      # use match
      elsif (match = my_re2.match(li ne)):
      # use match
      elsif (match = my_re3.match(li ne))
      # use match
      >
      ...buy this is illegal in python. The other way is to open up an else:
      block in each level, do the assignment and then the test. This
      unneccessarily leads to deeper and deeper nesting levels which I find
      ugly.
      How about this (untested) code:

      for re in (re1, re2, re3):
      match = re.match(line)
      if match:
      # use it

      This requires that "use it" means the same for each regular expression
      though...

      Uli

      --
      Sator Laser GmbH
      Geschäftsführ er: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

      Comment

      • Bruno Desthuilliers

        #4
        Re: C-like assignment expression?

        boblatest@googl email.com a écrit :
        Hello,
        >
        I have an if-elif chain in which I'd like to match a string against
        several regular expressions. Also I'd like to use the match groups
        within the respective elif... block. The C-like idiom that I would
        like to use is this:
        >
        if (match = my_re1.match(li ne):
        # use match
        elsif (match = my_re2.match(li ne)):
        # use match
        elsif (match = my_re3.match(li ne))
        # use match
        <ot>
        Isn't it the third or fourth time this very same question pops up here ?
        Starts to look like a FAQ.
        </ot>

        The canonical solution is to iterate over a list of expression,func tion
        pairs, ie:

        def use_match1(matc h):
        # code here

        def use_match2(matc h):
        # code here

        def use_match3(matc h):
        # code here

        for exp, func in [
        (my_re1, use_match1),
        (my_re2, use_match2),
        (my_re3, use_match3)
        ]:
        match = exp.match(line)
        if match:
        func(match)
        break


        The alternate solution is Diez's Test object.

        HTH

        Comment

        • Hrvoje Niksic

          #5
          Re: C-like assignment expression?

          Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalid>
          writes:
          The canonical solution is to iterate over a list of
          expression,func tion pairs, ie:
          Although that solution is pretty, it is not the canonical solution
          because it doesn't cover the important case of "if" bodies needing to
          access common variables in the enclosing scope. (This will be easier
          in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
          IMHO closer to a canonical solution to this FAQ.

          Comment

          • boblatest@googlemail.com

            #6
            Re: C-like assignment expression?

            On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs .orgwrote:
            Although that solution is pretty, it is not the canonical solution
            because it doesn't cover the important case of "if" bodies needing to
            access common variables in the enclosing scope. (This will be easier
            in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
            IMHO closer to a canonical solution to this FAQ.
            Hello everybody,

            thanks for the various answers. I'm actually pretty puzzled because I
            expected to see some obvious solution that I just hadn't found before.
            In general I find Python more elegant and syntactically richer than C
            (that's where I come from), so I didn't expect the solutions to be a
            lot more verbose and/or ugly (no offense) than the original idea which
            would have worked if Python's assignment statement would double as
            expression, as in C.

            Thanks again,
            robert

            PS: Since I'm testing only three REs, and I only need the match
            results from one of them, I just re-evaluate that one.

            Comment

            • cokofreedom@gmail.com

              #7
              Re: C-like assignment expression?

              On May 21, 3:12 pm, "boblat...@goog lemail.com"
              <boblat...@goog lemail.comwrote :
              On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs .orgwrote:
              >
              Although that solution is pretty, it is not the canonical solution
              because it doesn't cover the important case of "if" bodies needing to
              access common variables in the enclosing scope. (This will be easier
              in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
              IMHO closer to a canonical solution to this FAQ.
              >
              Hello everybody,
              >
              thanks for the various answers. I'm actually pretty puzzled because I
              expected to see some obvious solution that I just hadn't found before.
              In general I find Python more elegant and syntactically richer than C
              (that's where I come from), so I didn't expect the solutions to be a
              lot more verbose and/or ugly (no offense) than the original idea which
              would have worked if Python's assignment statement would double as
              expression, as in C.
              >
              Thanks again,
              robert
              >
              PS: Since I'm testing only three REs, and I only need the match
              results from one of them, I just re-evaluate that one.
              Is it really a lot to change to have it

              if my_re1.match(li ne):
              match = my_re1.match(li ne)
              elseif my_re2.match(li ne):
              match = my_re2.match(li ne)
              elseif my_re3.match(li ne):
              match = my_re3.match(li ne)

              ?

              That reads clearly to me...

              Comment

              • Diez B. Roggisch

                #8
                Re: C-like assignment expression?

                boblatest@googl email.com wrote:
                On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs .orgwrote:
                >
                >Although that solution is pretty, it is not the canonical solution
                >because it doesn't cover the important case of "if" bodies needing to
                >access common variables in the enclosing scope. (This will be easier
                >in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
                >IMHO closer to a canonical solution to this FAQ.
                >
                Hello everybody,
                >
                thanks for the various answers. I'm actually pretty puzzled because I
                expected to see some obvious solution that I just hadn't found before.
                In general I find Python more elegant and syntactically richer than C
                (that's where I come from), so I didn't expect the solutions to be a
                lot more verbose and/or ugly (no offense) than the original idea which
                would have worked if Python's assignment statement would double as
                expression, as in C.
                Well, it's a design-decision - and I'm pretty ok with it being a bit verbose
                here - as it prevents a *great* deal of programming errors that would
                otherwise happen from accidentally writing a = b where a == b was meant.

                One could argue that regular expressions - which seem to be THE case where
                it bugs people - should offer a standard way that essentially works as my
                solution - by keeping state around, making series of tests easier.


                Diez

                Comment

                • Diez B. Roggisch

                  #9
                  Re: C-like assignment expression?

                  cokofreedom@gma il.com wrote:
                  On May 21, 3:12 pm, "boblat...@goog lemail.com"
                  <boblat...@goog lemail.comwrote :
                  >On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs .orgwrote:
                  >>
                  Although that solution is pretty, it is not the canonical solution
                  because it doesn't cover the important case of "if" bodies needing to
                  access common variables in the enclosing scope. (This will be easier
                  in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
                  IMHO closer to a canonical solution to this FAQ.
                  >>
                  >Hello everybody,
                  >>
                  >thanks for the various answers. I'm actually pretty puzzled because I
                  >expected to see some obvious solution that I just hadn't found before.
                  >In general I find Python more elegant and syntactically richer than C
                  >(that's where I come from), so I didn't expect the solutions to be a
                  >lot more verbose and/or ugly (no offense) than the original idea which
                  >would have worked if Python's assignment statement would double as
                  >expression, as in C.
                  >>
                  >Thanks again,
                  >robert
                  >>
                  >PS: Since I'm testing only three REs, and I only need the match
                  >results from one of them, I just re-evaluate that one.
                  >
                  Is it really a lot to change to have it
                  >
                  if my_re1.match(li ne):
                  match = my_re1.match(li ne)
                  elseif my_re2.match(li ne):
                  match = my_re2.match(li ne)
                  elseif my_re3.match(li ne):
                  match = my_re3.match(li ne)
                  >
                  ?
                  >
                  That reads clearly to me...
                  And wastes time. regular expressions can become expensive to match - doing
                  it twice might be hurtful.

                  Diez

                  Comment

                  • cokofreedom@gmail.com

                    #10
                    Re: C-like assignment expression?

                    >
                    And wastes time. regular expressions can become expensive to match - doing
                    it twice might be hurtful.
                    >
                    Diez
                    match = (my_re1.match(l ine) or my_re2.match(li ne)) or
                    my_re3.match(li ne)

                    ?

                    Comment

                    • Diez B. Roggisch

                      #11
                      Re: C-like assignment expression?

                      cokofreedom@gma il.com wrote:
                      >>
                      >And wastes time. regular expressions can become expensive to match -
                      >doing it twice might be hurtful.
                      >>
                      >Diez
                      >
                      match = (my_re1.match(l ine) or my_re2.match(li ne)) or
                      my_re3.match(li ne)
                      How do you know *which* of the three has matched then?

                      Diez

                      Comment

                      • cokofreedom@gmail.com

                        #12
                        Re: C-like assignment expression?

                        On May 21, 4:09 pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
                        cokofree...@gma il.com wrote:
                        >
                        And wastes time. regular expressions can become expensive to match -
                        doing it twice might be hurtful.
                        >
                        Diez
                        >
                        match = (my_re1.match(l ine) or my_re2.match(li ne)) or
                        my_re3.match(li ne)
                        >
                        How do you know *which* of the three has matched then?
                        >
                        Diez
                        Depends if the OP wants to know that...

                        Comment

                        • inhahe

                          #13
                          Re: C-like assignment expression?

                          one of the few things i miss from C is being able to use assignment in
                          expressions. that's the only thing, really.
                          also there's no switch/case, you have to use a dictionary of functions
                          instead, although i rarely need that, usually i just use elif.

                          <boblatest@goog lemail.comwrote in message
                          news:7df99fd4-21c9-49a1-ba65-e55794fd4c12@26 g2000hsk.google groups.com...
                          On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs .orgwrote:
                          >
                          >Although that solution is pretty, it is not the canonical solution
                          >because it doesn't cover the important case of "if" bodies needing to
                          >access common variables in the enclosing scope. (This will be easier
                          >in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
                          >IMHO closer to a canonical solution to this FAQ.
                          >
                          Hello everybody,
                          >
                          thanks for the various answers. I'm actually pretty puzzled because I
                          expected to see some obvious solution that I just hadn't found before.
                          In general I find Python more elegant and syntactically richer than C
                          (that's where I come from), so I didn't expect the solutions to be a
                          lot more verbose and/or ugly (no offense) than the original idea which
                          would have worked if Python's assignment statement would double as
                          expression, as in C.
                          >
                          Thanks again,
                          robert
                          >
                          PS: Since I'm testing only three REs, and I only need the match
                          results from one of them, I just re-evaluate that one.

                          Comment

                          • Diez B. Roggisch

                            #14
                            Re: C-like assignment expression?

                            cokofreedom@gma il.com wrote:
                            On May 21, 4:09 pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
                            >cokofree...@gm ail.com wrote:
                            >>
                            >And wastes time. regular expressions can become expensive to match -
                            >doing it twice might be hurtful.
                            >>
                            >Diez
                            >>
                            match = (my_re1.match(l ine) or my_re2.match(li ne)) or
                            my_re3.match(li ne)
                            >>
                            >How do you know *which* of the three has matched then?
                            >>
                            >Diez
                            >
                            Depends if the OP wants to know that...
                            Well, in *general* one wants that. So as a general-purpose solution this is
                            certainly *not* the way to go.

                            Diez

                            Comment

                            • cokofreedom@gmail.com

                              #15
                              Re: C-like assignment expression?

                              On May 21, 4:57 pm, "inhahe" <inh...@gmail.c omwrote:
                              one of the few things i miss from C is being able to use assignment in
                              expressions. that's the only thing, really.
                              also there's no switch/case, you have to use a dictionary of functions
                              instead, although i rarely need that, usually i just use elif.
                              One thing I hate from C is the assignment in expressions...F orcing
                              myself to write
                              0 == Something
                              rather than
                              Something == 0
                              just to make sure I was mistakenly assigning values in statements is
                              annoying, it ruins the ease of reading.

                              I kind of agree with the select:case, but I think a key issue is how
                              to implement it. Elif is reasonable for now.

                              Diez, true I guess, but then we haven't seen what these expressions
                              are, and why there has to be three.

                              Comment

                              Working...