Refactoring Your Code and Renaming
00:00 So after cleaning up the code comments, I want to do a bit of refactoring. I’ve noticed that having the file extensions hidden down towards the end of the script makes it a bit hard to know which image files is the script actually looking for.
00:16
And so I’d rather take this out and put it towards the top into a constant because that makes it easier to remove or add image files—for example, if you wouldn’t want to search for .jpg
files.
00:30
I will call this one IMAGE_EXTENSIONS
.
00:36 So I cut the tuple that I had down here so that I can paste it here. Now I’m going to define
00:46
IMAGE_EXTENSIONS
as these three image extensions here. But now if you wanted to add .svg
files, you could just say
00:59
, ".svg"
, and then the script would also move .svg
files. And having this tuple up here at the beginning of the script makes it a little easier to maybe understand what’s happening here and also to maintain it. All right.
01:16
And then I don’t really like the name practice_dir
here. If I want to make this a bit more general, an idea would be to call this FULL_PATH
.
01:26
So I’m going to say FULL_PATH
, copy this, and I have to paste it here, and there’s another use. Looks good. I think I caught all of the mentions of practice_dir
there and replaced them with FULL_PATH
. If you’re using a more advanced text editor, there’s good refactoring features that make this easier.
01:49
Or you could also use a search and replace. Now, I’m also going to move FULL_PATH
to the constants up here,
01:59
and I might actually get rid of this DIRECTORY
after my final test and move it all into just the FULL_PATH
constant. But let’s talk about this in a bit. For now, I think I’m good with this refactoring.
02:11
I like having added this IMAGE_EXTENSIONS
here and also renamed practice_dir
to just the general path, and that gives you a bit more flexibility in changing your script to maybe also work for other file paths later on.
02:27
Now to also keep the script docstring up to date, I’m going to add a short note about the IMAGE_EXTENSIONS
constant. You can define which image files to move by changing the `IMAGE_EXTENSIONS` constant.
02:52 That looks good to me. We did a bit of refactoring. In the next lesson, let’s do a final test run before then wrapping up the script for good.
Become a Member to join the conversation.