2

I am writing some python code (to work in conjuction with ArcGIS), and I have a simple statement that runs fine and does exactly what I am asking it to do, I just get a 'warning' from my scripting software (PyCharm) telling me:

  • Local variable 'row' value is not used
  • This inspection highlights local variables, parameters or local functions unused in scope.

I understand it is not used, because it is not needed. This is the only way (that I know of personally) to work out how many rows exist in a table.

Can someone tell me if there is a better (more correct) way of writing this??

cursor = arcpy.SearchCursor(my_table)
for row in cursor:
    count += 1
print count

Cheers

Benno
  • 109
  • 1
  • 16
  • 2
    Change `for row in cursor` to `for _ in cursor` – Bhargav Rao Jun 10 '15 at 01:22
  • I usually use `sum(1 for row in cursor)`, though I don't know if it'll do anything about the warning. Bhargav's suggestion of naming the unused variable `_` should help. – user2357112 Jun 10 '15 at 01:25
  • 1
    You should use arcpy's [Get Count](http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//0017000000n7000000.htm) – Markus Meskanen Jun 10 '15 at 01:26
  • @MarkusMeskanen I didn't realise this 'GetCount_management' was available, I will be modifying my code to use this instead. Thanks for your suggestion – Benno Jun 10 '15 at 01:35

1 Answers1

8

By convention if you're looping and don't intend to use the value you store the iterator in a variable named _. This is still a normal variable that gets each value in turn, but is taken to mean "I don't plan to use this value." To use this convention you'd rewrite your code as:

cursor = arcpy.SearchCursor(my_table)
for _ in cursor:
    count += 1
print count

See What is the purpose of the single underscore "_" variable in Python? to learn more about the single underscore variable.

But as Markus Meskanen pointed out there is a better way to solve this specific problem.

Community
  • 1
  • 1
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • 1
    Thanks Eric, your suggestion has satisfied the PyCharm formatting checker, it works well. I did not realise until Marcus suggested, but I should be using the ArcPy.GetCount_management() tool instead. Thanks for your time everyone – Benno Jun 10 '15 at 01:40
  • Yeah, Markus's suggestion is definitely the way to go here, but this is still good to know as the accepted convention for this situation should it come up again – Eric Renouf Jun 10 '15 at 01:41
  • You could have explained in a better manner as to what `_` is. :) Nevertheless you have clearly explained the usage. Hence +1 to you – Bhargav Rao Jun 10 '15 at 01:51
  • @BhargavRao I'll happily add to the answer if you think I wasn't clear that `_` is just a variable name like any other that by convention means "I don't plan to use this". – Eric Renouf Jun 10 '15 at 02:00
  • 1
    I have added a small link there. I think this makes the answer complete. – Bhargav Rao Jun 10 '15 at 02:05