Search code examples
pythonnonetype

How do I convert all python operations involving None to None values?


I want all mathematical operations involving one or more None variables to return None.

Example:

a = None
b = 7
a*b 

I want this last line to return None, but it instead gives me an error:

TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

I understand why this error exists and all that, but is there any way to force the result to be just a None?

Background: I have a few functions that mine data and return a value, called diff. Later on I multiply or add diff to a few things to get meaningful information, but not all of my original data contains a useful diff, so I have it set to return diff = None in these cases. I want to be able to skip over these points when I'm plotting results. Python seems to have no trouble skipping over None elements in an array when I'm plotting, so I'd like to just have the results of the operations be None.


Solution

  • Instead of trying to force all mathematical operations that contain some arbitrary other value to return that arbitrary other value, you could simply use a NaN, which is designed for exactly this sort of purpose:

    >>> nan = float("NaN")
    >>> 7 * nan
    nan
    >>> 7 + nan
    nan
    

    A nan will correctly cascade throughout your mathematical operations.

    A good plotting library will also understand nan and omit them at plot time. But if not, simply do your replacement of NaN to None immediately prior to plotting.