r/PythonLearning • • 1d ago

Discussion Where do you use None in python

So far I've only really used None in two places:

  1. With dict.get(), when the key isn't there.
  2. With del in classes. I set a variable to None so the object gets cleaned up.

Where else do you use it? Do you use it as a default value for function arguments, or for missing data?

 

I'm curious how people use it in real projects.

14 Upvotes

14 comments sorted by

View all comments

1

u/Atmosck 21h ago edited 21h ago

If you use type annotations (and you should), it's all over the place. For example, it's common to give functions optional arguments that default to none, then have some logic to determine the behavior in that case.

from datetime import date

def some_function(as_of: date | None = None):
  if as_of is None:
      as_of = date.today()
  ...

Another example is for an attribute of a class that might not always exist. A very common pattern is to define something as a _private attribute that can be none, with a corresponding \@property that resolves it. For example with machine learning, you often have components or values that don't exist before the thing is fitted.

class TemperatureScalingCalibrator:
    def __init__(self) -> None:
        self._temperature: float | None = None

    @property
    def temperature(self) -> float:
        if self._temperature is None:
            raise RuntimeError("EventTemperatureCalibrator must be fitted before its temperature is read.")
        return self._temperature

    def fit(self, raw, actual) -> TemperatureScalingCalibrator:
        ...
        self._temperature = float(np.exp(log_temperature))
        return self

Then consider something like this:

calibrator = TemperatureScalingCalibrator()
temp: float = calibrator._temperature # type checkers complain about this
temp: float = calibrator.temperature  # type checkers are chill about this

Your type checker knows that _temperature could be either a float or None, so it complains if you try to do something you can't do with a None, like assign it to a variable typed as a float. But the type checker knows that temperature (no underscore) will always be a float if you get as far as the temperature() property returning a value, so you can do float stuff with it.