Refactoring Code
00:00 There is no real new content in this lesson, so I’ll go through this quite quickly. You’re just going to add some more structure to the code to then, in the next lesson, incorporate persisting the index.
00:12
You’re going to make four changes. So firstly, build a get_index() function that takes all the loading and indexing functionality, then build a main() function that calls that get_index() function and does everything else, like creating the query engine and getting user input and all that, and then builds the usual if __name__ == "__main__" structure, and that then calls the main() function.
00:38
And then finally, you’ll also refine the user prompt a little bit to make it a bit more user-friendly. So this is what the refactored code looks like. If you start on line 17, this is the get_index() function.
00:50
As you can see, it creates a reader object as before,
00:54
creates a documents list, and then creates the index. Of course, then you have to return the index. If you then move to line 4, that is where your main() function starts.
01:04
It starts by calling the get_index() function to then create the index, and then you create your query engine on line 6. On line 7 is the user input as before, but I’ve just added a little bit of functionality or a little bit of text, really, on lines 8 to 11.
01:22
I added "I work for Steven's Pythonistas Limited" so that the user doesn’t have to type that every time. And then at the end on line 11, I’ve added "Please explain why. Thank you!" Just because, as we’ve seen in the previous lesson, that gives you better response.
01:39
The only thing left to discuss is line 24, where you have your if __name__ == "__main__" structure which calls the main() function.
Become a Member to join the conversation.
