Answer a question

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()

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.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐