1

The function os.path.split for example return a tuple of head and tail. I must specify both parts of the tuple but if I only need one of them pylint complains about an unused parameter. What is the proper way to do this in python?

(head, tail) = os.path.split("a/b/c")
5
  • 4
    If you need only head, try head, _ or if you need only tail, use _, tail. Jun 13, 2019 at 12:24
  • 1
    head = os.path.split("a/b/c")[0] also works. Not as slick looking, but it avoids making an unnecessary binding. Jun 13, 2019 at 12:26
  • For what it's worth: since Python 3.5, you can do e.g. a, *_ = "a/b/c".split('/') to skip multiple parts (and, vice versa, *_, c = "a/b/c".split('/'); but (obviously) not *_, b, *_ = "a/b/c".split('/')).
    – 9769953
    Jun 13, 2019 at 12:27
  • 1
    @JohnColeman Assumes an indexable iterable (probably reasonable here)- or else next(iter(iterable)) would be an alternative Jun 13, 2019 at 12:33
  • @Chris_Rands Good point, though OP did specify tuples. Jun 13, 2019 at 13:12

3 Answers 3

4

You can use _:

head, _ = os.path.split("a/b/c")

This is a convention that most IDEs use to interpret that the programmer is not interested in that value, however, the _ is a legal variable name and will point to the value being "ignored":

>>> x = (1, 2, 3, 4)
>>> _, *middle, _ = x
>>> _
4

You can even use something like this if you are having more than two values:

>>> x = (1, 2, 3, 4)
>>> x
(1, 2, 3, 4)
>>> first, *middle, last = x
>>> first
1
>>> middle
[2, 3]
>>> last
4

Therefore, you can still use _ to "ignore" some parts of a pattern, like so:

>>> x = (1, 2, 3, 4)
>>> x
(1, 2, 3, 4)
>>> _, *middle, _ = x
>>> middle
[2, 3]
0
3

The standard way to do this is to use _.

For example:

head, _ = os.path.split("a/b/c")

1

use the underscore to indicate that a variable is expected but you do't want to use it.

For example use:

   head, _ = os.path.split("a/b/c")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.