Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

Note that we're talking about a function that returns something which you cannot change.

def fn():     return 5 

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

null = fn() 
like image 858
PascalVKooten Avatar asked Oct 08 '14 07:10

PascalVKooten


People also ask

How do I ignore one return value in Python?

1 Answer. To Ignore python multiple return value you can use the "_" as a variable name for the elements of the tuple.

How do you stop a Python function when a certain condition is met?

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running. It is the most reliable, cross-platform way of stopping code execution.

What happens if you don't return a value from a function Python?

If a function doesn't specify a return value, it returns None . In an if/then conditional statement, None evaluates to False.


1 Answers

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.

like image 148
Daniel Roseman Avatar answered Oct 03 '22 17:10

Daniel Roseman