Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Foundational Concepts
Lecture: Testing for None
0:01 Next let's look at testing for a special case.
0:03 Imagine that we are going to call a function and that might return a list
0:06 and that list might have items in it or it might not,
0:10 maybe we are trying to do some kind of search and there is just no results,
0:13 and yet, if it was an unable to perform a search,
0:16 we'd like to indicate that differently than if there is just no results.
0:19 In that case, we can actually change our algorithm just a little bit
0:22 and test for something different.
0:24 Let's look at PyCharm.
0:26 So here I have this function called find_accounts
0:27 and you give it some search text;
0:29 it checks to see if the database was available and if it's not available,
0:34 it returns None, which we know is False.
0:36 Otherwise, it's going to actually do a search against our database
0:40 and return a list of account ids.
0:42 However, there might not be any matching results
0:45 in which case that list could be empty,
0:47 so you might be tempted to say "if not accounts",
0:50 then maybe I want to just like print something out like this,
0:54 "else", let's actually try to say we are going to print the accounts.
0:57 This part is going to work fine if there are results, we would list them.
1:00 However, it could be that our search just returns no results,
1:04 in which case this list would evaluate the False,
1:06 so we are going to change this, we are going to test actually if accounts is None,
1:10 when you are testing against singletons, and None is a singleton,
1:14 there is only one instance of it per process,
1:16 we'll use "is" and that actually compares at the pointers,
1:20 not just the inherit truthiness of the objects
1:22 or some kind of overloaded comparison operator.
1:25 So now our code is going to work as expected,
1:29 if we literally get nothing back because the DB is unavailable,
1:32 then we can say oh, DB is not available, otherwise, we might print them out.
1:36 And of course, that set might be empty,
1:37 we might want to put in additional testing here to say
1:40 "well, if it's empty" like your search works but there is no results, whatever.
1:44 But the Pythonic thing here is to notice that we are using "is"
1:48 to test against singleton and a special case of singletons
1:51 of course is the None keyword, which is one of the most common.
1:56 So here we have this in a graphic, so we are calling find_accounts,
1:59 giving it some search text and we are going to get some results back
2:02 and we want to make sure that not only is it truthy,
2:06 but it's actually worth specifically testing that there is something we got back
2:10 rather than a None pointer,
2:12 so "if accounts is not None",
2:15 and notice, when you negate "is", you say "is not",
2:18 rather "than not account is", which would also work but is less Pythonic.