How to elegantly ignore some return values of a Python function? How to elegantly ignore some return values of a Python function? python python

How to elegantly ignore some return values of a Python function?


The standard way to show this is to assign the results you don't want to _. For instance, if a function returns two values but you only want the first, do this:

value, _ = myfunction(param)

Most Python linters will recognize the use of _ and not complain about unused variables.

If you want to ignore all returns, then simply don't assign to anything; Python doesn't do anything with the result unless you tell it to. Printing the result is a feature in the Python shell only.


I really like the idea of assigning to null - but it does have an unexpected side-effect:

>>> print divmod(5, 3)(1, 2)>>> x, null = divmod(5, 3)>>> print null2

For those who code mostly in Python, this is probably not an issue: null should be just as much a junk value as _.

However, if you're switching between other languages like Javascript, it's entirely possible to accidentally write a comparison with null instead of None. Rather than spitting the usual error about comparing with an unknown variable, Python will just silently accept it, and now you're getting true and false conditions that you totally don't expect... this is the sort of error where you stare at the code for an hour and can't figure out wth is wrong, until it suddenly hits you and you feel like an idiot.

The obvious fix doesn't work, either:

>>> x, None = divmod(5, 3)File "<stdin>", line 1SyntaxError: cannot assign to None

...which is really disappointing. Python (and every other language on the planet) allows all of the parameters to be implicitly thrown away, regardless of how many variables are returned:

>>> divmod(5, 3)

...but explicitly throwing away parameters by assigning them to None isn't allowed?

It feels kind of stupid of the Python interpreter to characterize assigning to None as a syntax error, rather than an intentional choice with an unambiguous result. Can anyone think of a rationale for that?