Python's None: Null in Python (Summary)
None is a powerful tool in the Python toolbox. Like
None is an immutable keyword. As the
null in Python, you use it to mark missing values and results, and even default parameters where it’s a much better choice than mutable types.
Now you can:
- Test for
- Choose when
Noneis a valid value in your code
Noneand its alternatives as default parameters
NoneTypein your tracebacks
Optionalin type hints
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
So, one of the first things I showed you is that
None is the return value of functions that don’t have a return value, or that don’t have an explicit return value. It’s an object, it’s a constant, and it’s a singleton, meaning that there is only one
If you really want to check if something is
None, you have to use the
is keyword, and this is because everything which
is None is pointing to the same instance of
None is an object, but there is a single instance of this object and all things which are
None are pointing to it. I also showed you how sometimes when you’re creating a function, or rather, when you are defining a function, if you’re using a mutable data type as a default parameter, this can get you into trouble.
The code in the function definition is only run once, when it’s first called, so this can lead to some unwanted behavior. Every time that you use this function without passing a parameter, it’s going to be using the first parameter, the default parameter, which was run when the function was first defined. And a way to get around this is to set default parameters to
Also, something that’s important to keep in mind here is that if you do need to accept
None as a valid input, the easiest way to do this is to create a class which you can use as a signal to not accept an input. That way you’re free to accept
None as an input if it comes up.
The last thing we saw in the video just before this one was how to deal with
None in tracebacks. So, often you’ll get a traceback when something which wasn’t expected to be
None turned out to be
None. There are three steps which you can use to deal with this sort of error.
02:13 This was the last lesson in our course. I hope you enjoyed it, I hope you learned something new, and I hope we’ll see you again on Real Python. Remember to practice what you learned today, and keep learning!
Become a Member to join the conversation.