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

12 comments sorted by

7

u/Money_Ad_5277 1d ago

"Find" functions, mostly.
Like def get_user_by_id(id: str) -> User | None
Or as flag like in random(seed: int | None)
Or to show absence of property/value

But generally when function should return no data

3

u/realmauer01 23h ago

Wouldnt you rather raise an exception in this case? The second one is a type, not really a flag.

3

u/Money_Ad_5277 23h ago

You can, and some projects do use this approach. I'm just not a fan of it, as not finding something isn't an error per se

0

u/realmauer01 23h ago

Well thats why its an exception. And its not like the boiler plate of handleling it goes away just because you pretend its not a problem. Try finding something but find nothing.

1

u/Money_Ad_5277 23h ago

Shouldn't handling it with "if" be cheaper computation/memory-wise?

We all have different opinions and maybe it's related to different examples we use to prove our point of view

4

u/Alexku66 1d ago

It's kinda everywhere. Each sentinel like `if not items: return` in fact returns None. When function modifies object in-place, or does something without the purpose to return anything, in fact it returns None. Each time you declare variable before using it in a loop, you assign None value first.

More than that, sometimes one None is not enough. When write API that updates existing object, say product in database, which description column is nullable. If you provide {"description" : None} , does it mean you want description to be empty (null) or to not update it? I usually create another class, UNSET, to explicitly state that this attribute is not updated

3

u/SaltCusp 1d ago

Default value for keyword args for sure.

2

u/Ngtuanvy 1d ago

None serves as an optional, when you want a variable to either hold say an integer or nothing, can't use 0 because 0 may be a valid value.

1

u/MarsupialLeast145 1d ago

I use it when I don't want any ambiguity in terms of assignment, or any conditional checks, on any variables. Code can become cleaner to write and easier to predict.

1

u/Potential_Fix_5007 1d ago

It can be important if you(or someone else) want/need to understand your code from month ago.

If you use any kind of check a None is a clear way to show "here is intentinaly no value". A zero (0) An empty string("") Empty List, Set or dict([], {})

All of these are falsy values and would be countet as "False" if you would do something like this:"if value:" or "while value:", but if you use something else than "None" i cant be sure if something else is a empty value by intention, so i may have to understand way more of your Programm just to fix something in a single function.

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.

1

u/HanTheGreatInventor 16h ago

Default value ofc.

func(x=None):
x=5 if x is None else x