Reputation: 910
I don't quite understand why Python will automatically convert any 0 returned to me by a function into a None object. I've programmed in almost all of the common languages, yet I've never come across this before. I would expect that if I set 0 in the result, I would get 0 back from the function.
Could anyone please explain why Python does this?
EDIT:
To give some more information, we have a wrapper around a C++ class and the return value type is a void pointer. So if it is returning an integer with a value of 0, it gives me a None type. Does this make sense to anyone?
I'm just new to Python and trying to figure out when I might expect None types rather than the return value.
Upvotes: 1
Views: 3936
Reputation: 122649
we have a wrapper around a C++ class and the return value type is a void pointer. So if it is returning an integer with a value of 0, it gives me a None type
0 is the value of the NULL
pointer in C++ (although you should refer to it as NULL
).
If you have a C++ function returning void*
type and you return 0
, you're effectively returning NULL
, therefore you're returning None
in Python.
You may be interested in this question: Do you use NULL or 0 (zero) for pointers in C++? (see nullptr
too).
Upvotes: 5
Reputation: 13088
Python doesn't enforce return types like Java so it is actually "quite easy" to forget to put in a return statement at the end of a function. This will cause the function to return None.
Upvotes: 1
Reputation: 14106
Just a wild guess, but if you're doing something like this:
def gives_none()
#does stuff
0
you've failed to realize that python needs an explicit return statement. While some languages will return zero here, that's not how Python works. Without an explicit return statement your function will return None
. Try:
def works():
#does stuff
return 0
Upvotes: 4