for loop without variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Guest's Avatar

    #16
    SV: Conventions for dummy name

    Torsten Bronger wrote:
    >Hallöchen!
    >
    >Ben Finney writes:
    >
    >"Diez B. Roggisch" <deets@nospam.w eb.dewrites:
    >>
    >>The underscore is used as "discarded" identifier. So maybe
    >>
    >>for _ in xrange(10):
    >> ...
    >>
    >The problem with the '_' name is that it is already well-known and
    >long-used existing convention for an entirely unrelated purpose:
    >in the 'gettext' i18n library, the '_' function to get the
    >locally-translated version of a text string.
    >
    >Right, that's because I've used "__" where not all returning values
    >are interesing to me such as
    >
    >a, b, __ = function_that_r eturns_three_va lues(x, y)
    Variable name "dummy" serves the same purpose, such as:

    a, b, dummy = function_that_r eturns_three_va lues(x, y)

    According to http://linux.die.net/man/1/pylint it is also possible to use the
    option

    --dummy-variables-rgx=<regexp>

    to further specify which variable not to report as unused. As far as I can
    tell, it defaults to '_|dummy'.

    ..david

    Comment

    • Duncan Booth

      #17
      Re: for loop without variable

      erik gartz <eegunnar@yahoo .comwrote:
      Hi. I'd like to be able to write a loop such as:
      for i in range(10):
      pass
      but without the i variable. The reason for this is I'm using pylint
      and it complains about the unused variable i. I can achieve the above
      with more lines of code like:
      i = 0
      while (i != 10):
      i += 1
      Is there a concise way to accomplish this without adding extra lines
      of codes? Thanks in advance for your help.

      Google for: pylint unused

      It pointed me at:
      Question:
      I've a function / method which is a callback where I do not have any
      control on received argument, and pylint is complaining about unused
      arguments. What can I do to avoid those warnings ?
      >
      Answer:
      prefix (ui) the callback's name by cb_, as in cb_onclick(...) . By doing
      so arguments usage won't be checked. Another solution is to use one of
      the name defined in the "dummy-variables" configuration variable for
      unused argument ("_" and "dummy" by default).


      So it looks like you can use 'dummy' or add any other names you want to the
      configuration.

      Comment

      • Torsten Bronger

        #18
        Re: Conventions for dummy name

        Hallöchen!

        David.Reksten@s weco.no writes:
        Torsten Bronger wrote:
        >
        >[...]
        >>
        >Right, that's because I've used "__" where not all returning
        >values are interesing to me such as
        >>
        >a, b, __ = function_that_r eturns_three_va lues(x, y)
        >
        Variable name "dummy" serves the same purpose, such as:
        >
        a, b, dummy = function_that_r eturns_three_va lues(x, y)
        Granted, but my rationale is that "__" is less visible in the source
        code, so there is more emphasis on the actually interesting
        variables.

        Tschö,
        Torsten.

        --
        Torsten Bronger, aquisgrana, europa vetus
        Jabber ID: bronger@jabber. org
        (See http://ime.webhop.org for further contact info.)

        Comment

        • Guest's Avatar

          #19
          SV: Conventions for dummy name

          Torsten Bronger writes:
          >David.Reksten@ sweco.no writes:
          >
          >Torsten Bronger wrote:
          >>
          >>[...]
          >>>
          >>Right, that's because I've used "__" where not all returning
          >>values are interesing to me such as
          >>>
          >>a, b, __ = function_that_r eturns_three_va lues(x, y)
          >>
          >Variable name "dummy" serves the same purpose, such as:
          >>
          > a, b, dummy = function_that_r eturns_three_va lues(x, y)
          >
          >Granted, but my rationale is that "__" is less visible in the source
          >code, so there is more emphasis on the actually interesting
          >variables.
          I guess it's a matter of preference. Personally, I find "dummy" to be more
          explicit, and hence more readable for those that that will read my code
          later. YMMV.

          Regards,
          ..david

          Comment

          • Mike Meyer

            #20
            Re: for loop without variable

            On Thu, 10 Jan 2008 08:42:16 +0100 Hrvoje Niksic <hniksic@xemacs .orgwrote:
            Mike Meyer <mwm-keyword-python.b4bdba@m ired.orgwrites:
            It sounds to me like your counter variable actually has meaning,
            It depends how the code is written. In the example such as:
            >
            for meaningless_var iable in xrange(number_o f_attempts):
            ...
            >
            the loop variable really has no meaning. Rewriting this code only to
            appease pylint is exactly that, it has nothing with making the code
            more readable.
            Except in this case, the variable *has* a meaning. You've just chosen
            to obfuscate it.
            you've hidden that meaning by giving it the meaningless name "i". If
            you give it a meaningful name, then there's an obvious way to do it
            (which you listed yourself):

            while retries_left:
            [...]
            >
            This loop contains more code and hence more opportunities for
            introducing bugs. For example, if you use "continue" anywhere in the
            loop, you will do one retry too much.
            All correct - and I'm a big fan of minimizing code, as code you don't
            write has no bugs in it. But you can still show the meaning of this
            "meaningles s" variable:

            for number_of_attem pts in xrange(maximum_ attempts):

            Of course, the OP's request is a better solution: since he doesn't
            actually need the variable, removing it completely means there's one
            less variable, which is one less thing you can set to the wrong value.

            <mike
            --
            Mike Meyer <mwm@mired.or g> http://www.mired.org/consulting.html
            Independent Network/Unix/Perforce consultant, email for more information.

            Comment

            • Basilisk96

              #21
              Re: for loop without variable

              On Jan 9, 10:55 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
              wrote:
              erik gartz <eegun...@yahoo .comwrites:
              The loop performs some actions with web services. The particular
              iteration I'm on isn't important to me. It is only important that I
              attempt the web services that number of times. If I succeed I
              obviously break out of the loop and the containing function (the
              function which has the loop in it) returns True. If all attempts
              fail the containing loop returns False.
              >
              When you have iteration requirements that don't seem to fit the
              built-in types (lists, dicts, generators etc.), turn to 'itertools'
              <URL:http://www.python.org/doc/lib/module-itertoolsin the standard
              library.
              >
              >>from itertools import repeat
              >
              >>def foo():
              ... import random
              ... print "Trying ..."
              ... success = random.choice([True, False])
              ... return success
              ...
              >>max_attempt s = 10
              >>for foo_attempt in repeat(foo, max_attempts):
              ... if foo_attempt():
              ... break
              ...
              Trying ...
              Trying ...
              Trying ...
              Trying ...
              Trying ...
              Trying ...
              >>>
              >
              Note that this is possibly more readable than 'for foo_attempt in
              [foo] * max_attempts", and is more efficient for large values of
              'max_attempts' because 'repeat' returns an iterator instead of
              actually allocating the whole sequence.
              >
              I guess based on the replies of everyone my best bet is to leave the
              code the way it is and suck up the warning from pylint.
              >
              I think your intent -- "repeat this operation N times" -- is better
              expressed by the above code, than by keeping count of something you
              don't actually care about.
              >
              I don't want to turn the warning off because catching unused
              variables in the general is useful to me.
              >
              Agreed.
              >
              --
              \ "Dyslexia means never having to say that you're ysror." |
              `\ --anonymous |
              _o__) |
              Ben Finney
              Neat! That is the best solution I've seen so far. I should definitely
              dig into the itertools module more often.

              Cheers,
              -Basilisk96

              Comment

              • Marty

                #22
                Re: for loop without variable

                Hrvoje Niksic wrote:
                Mike Meyer <mwm-keyword-python.b4bdba@m ired.orgwrites:
                >
                >It sounds to me like your counter variable actually has meaning,
                >
                It depends how the code is written. In the example such as:
                >
                for meaningless_var iable in xrange(number_o f_attempts):
                ...
                >
                the loop variable really has no meaning. Rewriting this code only to
                appease pylint is exactly that, it has nothing with making the code
                more readable.
                >
                >you've hidden that meaning by giving it the meaningless name "i". If
                >you give it a meaningful name, then there's an obvious way to do it
                >(which you listed yourself):
                >>
                > while retries_left:
                [...]
                >
                This loop contains more code and hence more opportunities for
                introducing bugs. For example, if you use "continue" anywhere in the
                loop, you will do one retry too much.
                I recently faced a similar issue doing something like this:

                data_out = []
                for i in range(len(data_ in)):
                data_out.append ([])

                This caused me to wonder why Python does not have a "foreach" statement (and
                also why has it not come up in this thread)? I realize the topic has probably
                been beaten to death in earlier thread(s), but does anyone have the short answer?

                Comment

                • Ryan Ginstrom

                  #23
                  RE: for loop without variable

                  On Behalf Of Marty
                  I recently faced a similar issue doing something like this:
                  >
                  data_out = []
                  for i in range(len(data_ in)):
                  data_out.append ([])
                  >
                  This caused me to wonder why Python does not have a "foreach"
                  statement (and also why has it not come up in this thread)?
                  I realize the topic has probably been beaten to death in
                  earlier thread(s), but does anyone have the short answer?
                  data_out = [[] for item in data_in]

                  Regards,
                  Ryan Ginstrom

                  Comment

                  • Mike Meyer

                    #24
                    Re: for loop without variable

                    On Thu, 10 Jan 2008 22:36:56 -0500 Marty <martyb1@earthl ink.netwrote:
                    I recently faced a similar issue doing something like this:
                    >
                    data_out = []
                    for i in range(len(data_ in)):
                    data_out.append ([])
                    More succinctly:

                    data_out = []
                    for _ in data_in:
                    data_out.append ([])

                    Or, as has already been pointed out:

                    data_out = [[] for _ in data_in]
                    This caused me to wonder why Python does not have a "foreach" statement (and
                    also why has it not come up in this thread)? I realize the topic has probably
                    been beaten to death in earlier thread(s), but does anyone have the short answer?
                    But I'm curious - what's the difference between the "foreach" you have
                    in mind and the standard python "for"?

                    <mike
                    --
                    Mike Meyer <mwm@mired.or g> http://www.mired.org/consulting.html
                    Independent Network/Unix/Perforce consultant, email for more information.

                    Comment

                    • Matimus

                      #25
                      Re: for loop without variable

                      On Jan 10, 10:36 pm, Marty <mart...@earthl ink.netwrote:
                      Hrvoje Niksic wrote:
                      Mike Meyer <mwm-keyword-python.b4b...@m ired.orgwrites:
                      >
                      It sounds to me like your counter variable actually has meaning,
                      >
                      It depends how the code is written. In the example such as:
                      >
                      for meaningless_var iable in xrange(number_o f_attempts):
                      ...
                      >
                      the loop variable really has no meaning. Rewriting this code only to
                      appease pylint is exactly that, it has nothing with making the code
                      more readable.
                      >
                      you've hidden that meaning by giving it the meaningless name "i". If
                      you give it a meaningful name, then there's an obvious way to do it
                      (which you listed yourself):
                      >
                      while retries_left:
                      [...]
                      >
                      This loop contains more code and hence more opportunities for
                      introducing bugs. For example, if you use "continue" anywhere in the
                      loop, you will do one retry too much.
                      >
                      I recently faced a similar issue doing something like this:
                      >
                      data_out = []
                      for i in range(len(data_ in)):
                      data_out.append ([])
                      >
                      This caused me to wonder why Python does not have a "foreach" statement (and
                      also why has it not come up in this thread)? I realize the topic has probably
                      been beaten to death in earlier thread(s), but does anyone have the short answer?
                      Pythons `for' essentially is foreach. The code below does the same
                      thing as what you have posted does. Actually, I've found that if you
                      find yourself ever doing range(len(data_ in)) in python, it is time to
                      take a second look.

                      data_out = []
                      for x in data_in:
                      data_out.append ([])

                      `range' is just a function that returns a list.

                      Matt

                      Comment

                      • Paul Rubin

                        #26
                        Re: for loop without variable

                        erik gartz <eegunnar@yahoo .comwrites:
                        The loop performs some actions with web services. The particular
                        iteration I'm on isn't important to me. It is only important that I
                        attempt the web services that number of times. If I succeed I
                        obviously break out of the loop and the containing function (the
                        function which has the loop in it) returns True. If all attempts fail
                        the containing loop returns False.
                        This uses an index var, but doesn't leak it outside the genexp, so
                        I don't know what pylint would say (untested):

                        def f():
                        return any(attempt_ser vice() for i in xrange(10))

                        I think the above is pretty natural. If you really insist on not
                        using any variables, the below might work (untested):

                        from itertools import imap, repeat

                        def f():
                        return any(imap(apply, repeat(attempt_ service, 10)))

                        it just seems way too obscure though. Python style seems to favor
                        spewing extra variables around.

                        Comment

                        • Paul Rubin

                          #27
                          Re: for loop without variable

                          Mike Meyer <mwm-keyword-python.b4bdba@m ired.orgwrites:
                          data_out = [[] for _ in data_in]
                          ...
                          But I'm curious - what's the difference between the "foreach" you have
                          in mind and the standard python "for"?
                          The "for" loop, like the list comprehension, pollutes the namespace
                          with an index variable that's not used for anything. I prefer genexps:

                          data_out = list([] for x in data_in)

                          Comment

                          • Carl Banks

                            #28
                            Re: for loop without variable

                            On Thu, 10 Jan 2008 22:36:56 -0500, Marty wrote:
                            I recently faced a similar issue doing something like this:
                            >
                            data_out = []
                            for i in range(len(data_ in)):
                            data_out.append ([])
                            >
                            This caused me to wonder why Python does not have a "foreach" statement
                            (and also why has it not come up in this thread)? I realize the topic
                            has probably been beaten to death in earlier thread(s), but does anyone
                            have the short answer?
                            Most languages that have "foreach" use it the same way Python uses
                            "for". The reason they use "foreach" instead of plain "for" is often
                            because they have a separate for statement that mimic C's for.

                            Perhaps you're wondering why there is no syntax for looping a given
                            number of times. (Languages that have this feature, e.g., Ada, often to
                            use "repeat" as the keyword.)

                            1. Looping a fixed number of times is quite uncommon.
                            2. A syntax for it buys you almost nothing.


                            Carl Banks

                            Comment

                            • Marty

                              #29
                              Re: for loop without variable

                              Mike Meyer wrote:
                              On Thu, 10 Jan 2008 22:36:56 -0500 Marty <martyb1@earthl ink.netwrote:
                              >I recently faced a similar issue doing something like this:
                              >>
                              > data_out = []
                              > for i in range(len(data_ in)):
                              > data_out.append ([])
                              >
                              More succinctly:
                              >
                              data_out = []
                              for _ in data_in:
                              data_out.append ([])
                              >
                              Or, as has already been pointed out:
                              >
                              data_out = [[] for _ in data_in]
                              That's nice.
                              >
                              >This caused me to wonder why Python does not have a "foreach" statement (and
                              >also why has it not come up in this thread)? I realize the topic has probably
                              >been beaten to death in earlier thread(s), but does anyone have the short answer?
                              >
                              But I'm curious - what's the difference between the "foreach" you have
                              in mind and the standard python "for"?
                              >
                              <mike
                              For example, I thought the python "equivalent " of perl's foreach might be:

                              data_out = [[] foreach data_in]

                              Trying to answer my own question, if it comes down to a choice between a unique
                              statement v. the anonymous variable "_", then I guess I can see why Python did
                              it this way.

                              Comment

                              • Basilisk96

                                #30
                                Re: for loop without variable

                                On Jan 10, 10:36 pm, Marty <mart...@earthl ink.netwrote:
                                Hrvoje Niksic wrote:
                                Mike Meyer <mwm-keyword-python.b4b...@m ired.orgwrites:
                                >
                                It sounds to me like your counter variable actually has meaning,
                                >
                                It depends how the code is written. In the example such as:
                                >
                                for meaningless_var iable in xrange(number_o f_attempts):
                                ...
                                >
                                the loop variable really has no meaning. Rewriting this code only to
                                appease pylint is exactly that, it has nothing with making the code
                                more readable.
                                >
                                you've hidden that meaning by giving it the meaningless name "i". If
                                you give it a meaningful name, then there's an obvious way to do it
                                (which you listed yourself):
                                >
                                while retries_left:
                                [...]
                                >
                                This loop contains more code and hence more opportunities for
                                introducing bugs. For example, if you use "continue" anywhere in the
                                loop, you will do one retry too much.
                                >
                                I recently faced a similar issue doing something like this:
                                >
                                data_out = []
                                for i in range(len(data_ in)):
                                data_out.append ([])
                                >
                                This caused me to wonder why Python does not have a "foreach" statement (and
                                also why has it not come up in this thread)? I realize the topic has probably
                                been beaten to death in earlier thread(s), but does anyone have the short answer?
                                But it does:

                                data_in = (1,2,3,4,5)
                                data_out = []

                                data_out += [[] for blah in data_in]

                                print data_out
                                [[], [], [], [], []]


                                Cheers,
                                -Basilisk96

                                Comment

                                Working...