How can I get around declaring an unused variable in a for loop?

后端 未结 10 1156
自闭症患者
自闭症患者 2020-11-27 16:03

If I have a list comprehension (for example) like this:

[\'\' for x in myList]

Effectively making a new list that has an empty string for e

相关标签:
10条回答
  • 2020-11-27 16:46

    It turns out that using dummy* (starting word is dummy) as the variable name does the same trick as _. _ is a known standard and it would be better to use meaningful variable names. So you can use dummy, dummy1, dummy_anything. By using these variable names PyLint won't complain.

    0 讨论(0)
  • 2020-11-27 16:46

    The generator objects don't actually use the variables. So something like

    list(('' for x in myList))
    

    should do the trick. Note that x is not defined as a variable outside of the generator comprehension.

    0 讨论(0)
  • 2020-11-27 16:49

    Try it, it's simple:

    # Use '_' instead of the variable
    for _ in range(any_number):
        do_somthing()
    
    0 讨论(0)
  • 2020-11-27 16:50

    _ is a standard placeholder name for ignored members in a for-loop and tuple assignment, e.g.

    ['' for _ in myList]
    
    [a+d for a, _, _, d, _ in fiveTuples]
    

    BTW your list could be written without list comprehension (assuming you want to make a list of immutable members like strings, integers etc.).

    [''] * len(myList)
    
    0 讨论(0)
  • 2020-11-27 16:52

    If you need to name your arguments (in case, for example, when writing mocks that don't use certain arguments that are referenced by name), you can add this shortcut method:

    def UnusedArgument(_):
      pass
    

    and then use it like this

    def SomeMethod(name_should_remain):
      UnusedArgument(name_should_remain)
    
    0 讨论(0)
  • 2020-11-27 16:58

    You can also prepend a variable name with _ if you prefer giving the variable a human readable name. For example you can use _foo, _foo1, _anything and PyLint won't complain. In a for loop, it would be like:

    for _something in range(10):
        do_something_else()
    

    edit: Add example

    0 讨论(0)
提交回复
热议问题