Extracting the a value from a tuple when the other values are unused

前端 未结 6 1286
一整个雨季
一整个雨季 2021-02-04 10:42

I have a tuple foo which contains something I don\'t care about and something I do.

foo = (something_i_dont_need, something_i_need)
<
6条回答
  •  后悔当初
    2021-02-04 11:13

    Both are acceptable, and I've seen both in production code. I think the choice upon the context, the intent, and the local style.

    There is also a third option where the code describes the unused value:

    _real, imaginary = foo

    I use all three within my code depending upon which is clearest:

    _, x = foo

    • When the tuple is small.
    • When there are few discarded values.
    • When there are few discarded values relative to the number of extracted values.
    • The reader probably knows the tuple's composition, and the composition of the whole tuple is important.
    • When it's customary to think about the structure of the tuple as a single unit

    x=foo[i]

    • When the tuple is large.
    • When there are many discarded values for some value of many.
    • When the reader probably knows the tuple's composition.
    • The rest of the tuple's values are completely and utterly irrelevant & offer no useful information for the reader.
    • When it's customary to think about the structure as a sequence.
    • When the tuple has uniform composition.
    • When it's customary to use an index for the datatype.
    • When the index is keyed in a loop.
    • When the reader's attention should be drawn to the index's value.

    _real, imaginary = foo

    • When the tuple is small.
    • When there are few discarded values.
    • When the reader probably doesn't know the tuple's composition.
    • When naming the discarded value gives the reader insight. (You can guess from this one line that foo is a complex number.)

提交回复
热议问题