Search code examples
pythoniterable-unpacking

Why isn't there an ignore special variable in python?


Let's say I want to partition a string. It returns a tuple of 3 items. I do not need the second item.

I have read that _ is used when a variable is to be ignored.

bar = 'asd cds'
start,_,end = bar.partition(' ')

If I understand it correctly, the _ is still filled with the value. I haven't heard of a way to ignore some part of the output.

Wouldn't that save cycles?

A bigger example would be

def foo():
    return list(range(1000))
start,*_,end = foo()

Solution

  • It wouldn't really save any cycles to ignore the return argument, no, except for those which are trivially saved, by noting that there is no point to binding a name to a returned object that isn't used.

    Python doesn't do any function inlining or cross-function optimization. It isn't targeting that niche in the slightest. Nor should it, as that would compromise many of the things that python is good at. A lot of core python functionality depends on the simplicity of its design.

    Same for your list unpacking example. Its easy to think of syntactic sugar to have python pick the last and first item of the list, given that syntax. But there is no way, staying within the defining constraints of python, to actually not construct the whole list first. Who is to say that the construction of the list does not have relevant side-effects? Python, as a language, will certainly not guarantee you any such thing. As a dynamic language, python does not even have the slightest clue, or tries to concern itself, with the fact that foo might return a list, until the moment that it actually does so.

    And will it return a list? What if you rebound the list identifier?