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

Show parent comment

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

1

u/TryToFindABetterUN 2m 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/TryToFindABetterUN 6m 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.