r/PythonLearning • u/ETL_Pipeline_Dev • 1d ago
Discussion Where do you use None in python
So far I've only really used None in two places:
- With dict.get(), when the key isn't there.
- 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
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.
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.
Then consider something like 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.