How to gracefully ignore some Python function return values?

Sometimes a function gives a return value that you just want to discard, rather than send to the output stream. What would be an elegant way to handle this?

Note that we are talking about a function that returns something that you cannot change.

def fn(): return 5 

I personally used null before, but I'm looking for a more pythonic way:

 null = fn() 
+7
python return-value
source share
2 answers

The standard way to show this is to assign results that you do not want to use _ . For example, if a function returns two values, but you want only the first, do the following:

 value, _ = myfunction(param) 

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

If you want to ignore all returns, just do not assign anything; Python does nothing with the result unless you report it. Printing the result is a property only in the Python shell.

+13
source share

I really like the idea of ​​nulling - but it has an unexpected side effect:

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

For those who work primarily in Python, this is probably not a problem: the null value should be as significant as _.

However, if you switch between other languages ​​such as Javascript, it is entirely possible to accidentally write a comparison with a null value instead of None. Instead of spitting out the usual error when comparing with an unknown variable, Python just silently accepts it, and now you get true and false conditions that you do not fully expect ... this is such an error when you look at the code for an hour and do not can understand that wth is untrue until he suddenly hits you and you feel like an idiot.

The obvious fix does not work:

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

... which is really disappointing. Python (and any other language on the planet) allows you to exclude all parameters, regardless of the number of returned variables:

 >>> divmod(5, 3) 

... but explicitly discarding parameters by setting them to None is not allowed?

It seems that the stupidity of the Python interpreter characterizes the purpose of None as a syntax error, and not an intentional choice with a clear result. Can anyone think of a rationale for this?

+4
source share

All Articles