Python __name__ value initialization and usage

Python is an interpreted language, whenever python interpreter reads the code file it executes all the code found in it. But before execution of the code their are few special variables which are defined.

One of the special global variables is __name__

1> When the python script file is called as a main program the __name__ variable get the value __main__ .  This is why we see the below commonly used code.

if __name__ == "__main__": doSomething

2> When the python script is used a module the variable __name__ get the value of the module name. If your script name is fibo.py when its is imported into another python script, the global variable __name__ will have the value as module name fibo.

>>import fibo
>>fibo.__name__ 'fibo'

 

__name__ is your goto choice if you want to use a script to perform one functionality when executed independently and also expose same and other functionality which can be reused by other code when imported as a module.

For example: sumsub.py

add(x,y):
    print(x+y)

sub(x,y):
    print(x-y)

if __name__ == __main__:
    sum(5,6)

The above code when called as main program will execute the conditional statement and return the sum. When the same sumsub.py is imported the functions sum and sub can be called independently for any values of x/y, it will not directly execute for values 5,6.

Leave a Reply

Your email address will not be published. Required fields are marked *