Mike
Mike

Reputation: 125

Return type error in python

So I'm getting this error on a line where I have a recursive call. The line where the error occurred looks something like: return some_func(x) - .2

TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'

I tried return some_func(x) - .2 and x not None and float(x) is True, and other tricks but unsuccessfully so far.

Thanks!

Upvotes: 0

Views: 481

Answers (3)

daknøk
daknøk

Reputation: 646

some_func(x) returns None, and you cannot subtract a float from None—that wouldn’t make any sense. Depending on your needs, you can either make sure some_func(x) never returns None (by changing the implementation of some_func), or do this:

y = some_func(x)
if y is not None:
    return y - .2
else:
    return None

The last two lines can be omitted, since functions in Python implicitly return None.

Upvotes: 3

Katriel
Katriel

Reputation: 123712

Your fix

return some_func(x) - .2 and x not None and float(x) is True

doesn't work for at least three reasons.

  1. Python lazily evaluates ands.

    That is, A and B evaluates A first, then if A is true it evaluates B. In your case, evaluating A causes an exception, so you never even get to B.

  2. The check for not being none is x is not None, not x not None.

  3. The problem is that some_func(x) is None, not that x is None. Checking the latter is irrelevant.


Anyway, the solution is not to subtract floats from a value that may be None. The best way to do this is to ensure that some_func never returns None, which you can do by modifying its code. The next best is to check the return value, which you can do as

output = some_func(x)
if output is not None:
    return output - 0.2

Note, by the way, that if a function doesn't return anything then it is considered as implicitly returning None. So the above code will return None if some_func did. This may also be the source of your problem.

Upvotes: 0

Levon
Levon

Reputation: 143082

Without seeing your code, the error message seems to imply that at some point your function some_func(x) returns None. As the message states, you subtraction operation between None and the float is not possible in Python.

Trace your function and make sure that it always returns a numeric value and that problem should not occur. Alternatively, change your code to check the return for None (as shown by @daknok) and avoid the problem that way - however, it's better to prevent the problem at the source IMO.

Note the excellent comment by @burhan Kahlid below too.

Upvotes: 0

Related Questions