views:

138

answers:

2

Is there a way to write the following function so that my IDE doesn't complain that column is an unused variable?

def get_selected_index(self):
    (path, column) = self._tree_view.get_cursor()
    return path[0]

In this case I don't care about the second item in the tuple and just want to discard the reference to it when it is unpacked.

+14  A: 

In Python the _ is often used as an ignored placeholder.

(path, _) = self._treeView.get_cursor()

You could also avoid unpacking as a tuple is indexable.

def get_selected_index(self):
    return self._treeView.get_cursor()[0][0]
KennyTM
It's worth noting that `_` is not any kind of syntactic magic, but a convention (of course, it's a convention recognised by IDEs and pylint, and Python conventions are pretty strong...)
detly
Python would be nothing without conventions!
fredley
Is this convention documented?
Nathan
@fredley - I'm not disputing that at all :) but still worth mentioning. @Nathan - ...maybe?
detly
The same is often used in Lua; I suspect it's a common theme in languages that support this sort of unpacking.
Glenn Maynard
It is common in OCaml and Haskell.
Gaius
And is also common in Prolog: in fact it is a little more than a convention, it is an anonymous variable (and can be repeated, without it meaning the same value) in a matching statement. IIRC Erlang handles it similarly.
Matthew Schinckel
@Gaius: I believe in Haskell it explicitly means "discard this value"; in Python `_` is still an assigned variable that you could in theory use just like any other variable.
me_and
The python command line interpreter "magically" assigns _ to the result of the last computation so if you run something but forget to store the return value, it will be captured for you in the `_` variable. It's a useful thing while doing interactive work. In the above case, I'd probably do indexing rather than unpacking though.
Noufal Ibrahim
+2  A: 

If you don't care about the second item, why not just extract the first one:

def get_selected_index(self):
    path = self._treeView.get_cursor()[0]
    return path[0]
Steven
Note that the return should now be `return path`, not `return path[0]`
Michael Mior
This is weaker, because it removes the assertion that there are exactly two items.
jleedev
@Michael Mior: I've rolled back your edit: Based on the original question, it should still be `path[0]` (`path` seems to be a sequence itself)
Steven
Sorry about that @Steven. I wasn't reading carefully enough. It was confusing because the definition of `path` in your code is different than that used by the OP.
Michael Mior