2

Given that I have single element iterable such as tuple

t = (1,)

Is there a preferred way of unpacking that tuple into a variable? There are many options, which have different pros and cons.

unpacked, = t    #  Elegant but easy to overlook.
(unpacked,) = t  #  Maybe a bit clunky?
unpacked, *_ = t #  Creates the impression, that there might be more elements.
unpacked = t[0]  #  Same as above.
*_, unpacked = t #  Same as above, but also gives the impression
                 #  that we are accessing the last element.
[unpacked] = t   #  Elegant and obvious.

Does PEP8 have any recommendation on this?

Jarno
  • 6,243
  • 3
  • 42
  • 57
  • Don't think PEP8 makes a recommendation (although half od these weren't an option when it was written). I'd definitely prefer `t[0]` though. It's the one which is the most obvious without thinking about it. I'd definitely avoid the use of `*_` unless necessary. Although I must ask, why does the reader need to know if `t` is a singleton or not? They just care that `unpacked` is it's first element. – FHTMitchell Aug 30 '18 at 12:21
  • 1
    `t[0]` won't work for all iterables. `next(iter(t))` seems quite generic. – user2390182 Aug 30 '18 at 12:23
  • 1
    you could add `[unpacked] = t` – Chris_Rands Aug 30 '18 at 12:23
  • @FHTMitchell You are probably right, that the reader does not need to care about the singleton nature of `t`. However, I thought we would be nice to make it obvious, that we are not discarding any returned values. Is there a particular reason for avoiding `*_`? – Jarno Aug 30 '18 at 12:32
  • I'd just avoid `*_` just because it's not pretty I suppose. People coming from scala may disagree... – FHTMitchell Aug 30 '18 at 12:36
  • 2
    @FHTMitchell: The prettiness isn't all that meaningful to me; I'd avoid `*_` because it allows for violations of the spec (that the iterable has *exactly* one element) to pass silently. If the iterable has 2 or more elements, the other elements are ignored, and you silently get one of them (first or last, depending on ordering chosen). Same goes for `t[0]`. `unpacked,`, `(unpacked,)`, and `[unpacked]` all avoid that; if your expectation is violated, you get an immediate and clear exception, rather than stumbling along potentially losing important data. – ShadowRanger Nov 08 '18 at 15:09

0 Answers0