开发者

Assignment to None

I have a function which returns 3 numbers, e.g.:

def numbers():
   return 1,2,3

usually I call this function to receive all three returned numbers e.g.:

a, b, c = numbers()

However, I have one cas开发者_如何学Ce in which I only need the first returned number. I tried using:

a, None, None = numbers()

But I receive "SyntaxError: assignment to None".

I know, of course, that I can use the first option I mentioned and then simply not use the "b" and "c" variables. However, this seems like a "waste" of two vars and feels like wrong programming.


a, _, _ = numbers()

is a pythonic way to do this. In Python 3, you could also use:

a, *_ = numbers()

To clarify _ is a normal variable name in Python, except it is conventionally used to refer to non-important variables.


Another way is of course a=numbers()[0], if you do not want to declare another variable. Having said this though, I generally use _ myself.


The way I do it:

a = numbers()[0]

Seeing as the type returned is a tuple, you can access it via index.

This solution keeps you from having to declare unused/meaningless variables such as "_". Most people don't mind unused variables, however my pylint is setup to warn me of such things as they could indicate potentially unused code, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜