for loop without variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • erik gartz

    for loop without variable

    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.
  • Diez B. Roggisch

    #2
    Re: for loop without variable

    erik gartz schrieb:
    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.
    The underscore is used as "discarded" identifier. So maybe


    for _ in xrange(10):
    ...


    works.

    Diez

    Comment

    • Thomas Heller

      #3
      Re: for loop without variable

      erik gartz schrieb:
      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.
      Pychecker won't complain if you rename 'i' to '_', IIRC:

      for _ in range(10):
      pass

      Thomas

      Comment

      • Ben Finney

        #4
        Conventions for dummy name (was: for loop without variable)

        "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.

        Since the number of programs that need to use something like 'gettext'
        (and therefore use the '_' function) is likely only to increase, it
        seems foolish to set one's program up for a conflict with that
        established usage.

        I've seen 'dummy' used as a "don't care about this value" name in
        other Python code. That seems more readable, more explicit, and less
        likely to conflict with existing conventions.

        --
        \ "It is forbidden to steal hotel towels. Please if you are not |
        `\ person to do such is please not to read notice." -- Hotel |
        _o__) sign, Kowloon, Hong Kong |
        Ben Finney

        Comment

        • MRAB

          #5
          Re: Conventions for dummy name (was: for loop without variable)

          On Jan 9, 11:17 pm, Ben Finney <bignose+hate s-s...@benfinney. id.au>
          wrote:
          "Diez B. Roggisch" <de...@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.
          >
          Since the number of programs that need to use something like 'gettext'
          (and therefore use the '_' function) is likely only to increase, it
          seems foolish to set one's program up for a conflict with that
          established usage.
          >
          I've seen 'dummy' used as a "don't care about this value" name in
          other Python code. That seems more readable, more explicit, and less
          likely to conflict with existing conventions.
          >
          Perhaps a "discarded" identifier should be any which is an underscore
          followed by digits.

          A single leading underscore is already used for "private" identifiers,
          but they are usually an underscore followed by what would be a valid
          identifier by itself, eg. "_exit".

          The convention would then be:

          2 underscores + valid_by_self + 2 underscores =special

          underscore + valid_by_self =private

          underscore + invalid_by_self =dummy

          Comment

          • Dan Sommers

            #6
            Re: for loop without variable

            On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote:
            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 ...
            What does that loop do? (Not the loop you posted, but the "real" loop
            in your application.) Perhaps python has another way to express what
            you're doing.

            For example, if you're iterating over the elements of an array, or
            through the lines of a file, or the keys of a dictionary, the "in"
            operator may work better:

            for thing in array_or_file_o r_dictionary:
            do_something_wi th(thing)

            HTH,
            Dan

            --
            Dan Sommers A death spiral goes clock-
            <http://www.tombstoneze ro.net/dan/ wise north of the equator.
            Atoms are not things. -- Werner Heisenberg -- Dilbert's PHB

            Comment

            • erik gartz

              #7
              Re: for loop without variable

              On Jan 9, 8:35 pm, Dan Sommers <m...@privacy.n etwrote:
              On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote:
              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 ...
              >
              What does that loop do? (Not the loop you posted, but the "real" loop
              in your application.) Perhaps python has another way to express what
              you're doing.
              >
              For example, if you're iterating over the elements of an array, or
              through the lines of a file, or the keys of a dictionary, the "in"
              operator may work better:
              >
              for thing in array_or_file_o r_dictionary:
              do_something_wi th(thing)
              >
              HTH,
              Dan
              >
              --
              Dan Sommers A death spiral goes clock-
              <http://www.tombstoneze ro.net/dan/ wise north of the equator.
              Atoms are not things. -- Werner Heisenberg -- Dilbert's PHB
              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.

              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 don't want
              to turn the warning off because catching unused variables in the
              general is useful to me. Unfortunately, I don't *think* I can shut the
              warning for that line or function off, only for the entire file.
              Pylint gives you a rating of your quality of code which I think is
              really cool. This is a great motivation and helps me to push to
              "tighten the screws". However it is easy to get carried away with your
              rating.:-)

              Comment

              • Basilisk96

                #8
                Re: for loop without variable

                On Jan 9, 9:49 pm, erik gartz <eegun...@yahoo .comwrote:
                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.
                Do you think you could apply something like this:

                def foo():print "fetching foo..."
                actions = (foo,)*5
                for f in actions:
                f()

                fetching foo...
                fetching foo...
                fetching foo...
                fetching foo...
                fetching foo...

                ...but not knowing your specific implementation, I may be off the wall
                here.

                Cheers,
                -Basilisk96

                Comment

                • Carl Banks

                  #9
                  Re: for loop without variable

                  On Wed, 09 Jan 2008 14:25:36 -0800, erik gartz wrote:
                  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.

                  IIRC, in pylint you can turn off checking for a particular symbol. I had
                  to edit a .pylintrc file (location may vary on Windows) and there was a
                  declaration in the file that listed symbols to ignore.

                  Last time I bothered running it, I added "id" to that list, since I use
                  it often (bad habit) and almost never use the builtin id, but still
                  wanted shadowing warnings for other symbols.


                  Carl Banks

                  Comment

                  • Ben Finney

                    #10
                    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.
                    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

                    Comment

                    • Mike Meyer

                      #11
                      Re: for loop without variable

                      On Wed, 9 Jan 2008 18:49:36 -0800 (PST) erik gartz <eegunnar@yahoo .comwrote:
                      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.
                      It sounds to me like your counter variable actually has meaning, but
                      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:
                      if this_succeeds() :
                      return True
                      retries_left -= 1

                      return False

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

                      Comment

                      • Sam

                        #12
                        Re: for loop without variable

                        Unfortunately, I don't *think* I can shut the
                        warning for that line or function off, only for the entire file.
                        Pylint gives you a rating of your quality of code which I think is
                        wrong :)

                        # pylint: disable-msg=XXXXX will only impact the current line!

                        $ cat -n dummy.py
                        1 for i in range(2): # pylint: disable-msg=W0612
                        2 print "foo"
                        3 for i in range(2):
                        4 print "foo"

                        pylint will not generate a warning on line 1, but will on line 3!

                        Cheers.

                        Sam




                        Comment

                        • Hrvoje Niksic

                          #13
                          Re: for loop without variable

                          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.

                          Comment

                          • Jeroen Ruigrok van der Werven

                            #14
                            Re: Conventions for dummy name (was: for loop without variable)

                            -On [20080110 00:21], Ben Finney (bignose+hates-spam@benfinney. id.au) wrote:
                            >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.
                            The same applies for Babel (http://babel.edgewall.org/) where we have _() in
                            similar vein to the gettext implementation.

                            --
                            Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org/ asmodai
                            イェルーン ラウフロッ ク ヴァン デル ウェルヴェ ン
                            http://www.in-nomine.org/ | http://www.rangaku.org/
                            With a nuclear fire of Love in our Hearts, rest easy baby, rest easy...

                            Comment

                            • Torsten Bronger

                              #15
                              Re: Conventions for dummy name

                              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)

                              However, in loops, I prefer real names, even if the loop variable
                              isn't used outside.

                              Tschö,
                              Torsten.

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

                              Comment

                              Working...