The world’s leading publication for data science, AI, and ML professionals.

Two tools that will boost your Python scripts.

if __name__ == 'main' and argparse (+ bonus)

These two tools that you will read here are going to increase exponentially the usability of your Python scripts.

Photo by Markéta Marcellová on Unsplash
Photo by Markéta Marcellová on Unsplash

If you have read a bunch of code or you’re developing some big project and you need to do more than one script you need to know what if name== ‘main’ is. A way to write your functions only one time and use it in all of your scripts.

And if you are trying to make a program than anybody can execute the argparse library will make it efficiently for you. A way to introduce help and different arguments to your code.

if name == ‘main’:

What’s about the name variable? When the python interpreter read a source file it first defines a few special variables. In this case, name is one of them.

And the main? You’ll know that your code may have different parts. The functions you’ve defined are one of them and the other one is the main part. Usually the main is where you use your functions in order to make your code accomplish what’s been designed for. As you know well, it’s not obligated to use functions but if you need to do a concrete thing more than one time it’s very desirable to encapsulate it inside a function with a self-explanatory name. And it’s a good way to work to organize the structure of your code with all the functions above the main part. Now you’ll understand why. It will make your work easier and more readable for some stranger. And that’s always a good thing. Who knows if the stranger could be you in just a couple of months after writing the code.

Ok, once understood the name variable and the ‘main’ one let’s take a look at what happens when we put it together. And the best way to do it is through an example.

Imagine you have a script desired to do whatever you want. And you’re building another script where you’ll need some of the functions created in the older one. What could you do? You could use the ancient habit of copy-paste. But this would add more lines in your code and it won’t be clear what the new script does. Too many things. It would be very useful to be able to import the functions created in the older scripts as we do with the libraries we usually work with (numpy, pandas, seaborn, etc.). Here is your solution:

if __name__ == 'main':

You put this line of code above the main part of your older script and all that follows properly indented as it was a normal if. That’s it. You’ve already prepared your code to import your functions. This won’t change at all what the script did before. In fact, if you execute it normally it would work properly.

But now if you decide to use the functions you’ve created you’ll only have to import the older script as it was a library. Imagine the name of the old script is old_script.py you’ll only have to put in the new one:

from old_script import this_function, that_function

and you have your old functions (and only the functions) in the new script.


argparse

Photo by Christopher Gower on Unsplash
Photo by Christopher Gower on Unsplash

Usually, your code is going to be executed by other people and they won’t open your code. So you’ll need to give them some kind of information or if your script needs some concrete input you’ll have to find a proper way for the user to put it. For example, if you are doing a sound analysis in your script you’ll need to input a sound.

The old-fashioned way to do this is entering the script, searching where the input treated is loaded and modify it for the sound that you want to analyze. This, sometimes it isn’t an easy task. Especially if the script is a long one or if the reader has problems understanding what the code does. So when we want our program to be used for a large number of persons or maybe for a non-tech person the argparse library will help us really well. It will give them a code description and it will say to the user what he has to input in order your code to run.

Argparse is a Python library that communicates your script with your terminal. It permits the coder to put some kind of flags (with its correspondent explanation) in its code to execute them from the terminal.

Let’s take a look at how it works.

import argparse
parser = argparse.ArgumentParser(description='''The purpose of this script is to with two given numbers save the result of its multiplication''', formatter_class=argparse.RawTextHelpFormatter)

Firstly we have the description of our script. As we can see above the script treated it’s (to make it easy) just a multiplier where you need to introduce the two terms. The formatter_class attribute only apports the way it will print this to the terminal. We will see it in a minute.

parser.add_argument('-ft', '--first_term', default=1, type=int, help='''First term to multiply''')

This addition of an argument is more interesting. We see two possible flags (‘-‘ and ‘- -‘) this works exactly the same way as a Linux terminal. One dash is the abbreviated form of the two dashes. We also have the type of the data that we will be introducing. A default value just in case the user doesn’t introduce one. And a help attribute that says what this argument does.

parser.add_argument('-st', '--second_term', default=1, type=int, help='''Second term to multiply''')

The second argument it has no mystery. It works exactly like the first one.

parser.add_argument('-od', '--output_directory', default='/home/toni_domenech/Python/Datasets/multiplication/', type=str, help='Output folder for the .txt')

This one contains where we want to save our multiplication result. Note that the type is a string because we are giving here a path. In this case, the output by default is a directory to my computer. So if the one who’s trying to run my code introduces here nothing the code won’t run properly.

Finally, let’s take a look at how to use these args to our code.

args = parser.parse_args()
args.first_term * args.second_term

Here we have the way to use them. We will use the flag’s name. And that’s it.

The way to execute this code is the same one as any other python script you’ve made before.

python script.py -h

It will give us the description of the script and all the flags to be filled with its descriptions.

Now let’s give them a value.

python script.py -ft=5 -st=7 -od='/my_computer/desktop/'

And that’s it!


If you have read this to the end, here comes a present:

How To Write Python Code Like A Senior Developer

In this story, you’ll find the secret tool to write Python as a senior developer using a super simple package.

If you have any doubt feel free to ask, I’ll be happy to answer. And if you like it you could give a clap! It will help others to find this story!

Thx!


Related Articles