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:25 Let's look at PyCharm.
0:27 So here I have this function called find the find accounts
0:29 and you give it some search text;
0:31 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:03 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:38 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:55 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 then notice when you negate is you say is not,
2:19 rather than not account is which would also work but is less Pythonic.