Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top