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

16 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 1d ago

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

4

u/Money_Ad_5277 1d 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 1d 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.

2

u/TryToFindABetterUN 9h ago

No. That is not an exception as you use it in most languages.

If you look for something in a list, there are two very likely outcomes. It exists in the list (and then you want to know where, ie index, or get the thing itself) or it doesn't, which is also a perfectly valid answer (and quite expected outcome a lot of the time).

An exception (error) would be to look for something in a list that does not exist itself (the reference to the list is missing) so you can't look for it. Or if you are looking for "nothing" in an existing list. Here I would expect exceptions.

1

u/Money_Ad_5277 1d 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

1

u/TryToFindABetterUN 9h ago

Quite often exception handling is more computationally "expensive" than a simple conditional clause. I can't say for certainty in Python, since I have not looked at the underlying code.

But there is also another issue. Exception handling often jumps to another part of the code, skipping code inbetween. So the flow of the code changes and it can be harder to see what happens for the programmer (you need to read the code more closely). With a conditional it is quite clear what block of code is skipped and what is executed.

1

u/terletsky 4h ago

Depends on the boundary. If you use, for example, onion architecture on API backend and have Repository class that’s used by Service class, Repository.get_user(user_id=user_id) returns None since DB record doesn’t exist. Service class sees this and raises UserNotFoundError which is caught on router an HTTPException(status_code=http_status.NOT_FOUND, message='User not found') is raised.

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 1d ago edited 1d 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 1d ago

Default value ofc.

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

1

u/Money_Ad_5277 6h ago

Not like that, but yeah. Also python have "or" operator, so
x = x or 5
Not sure when it was added but cool coalesce operator