What is __name__ ?
__name__ is a special built-in attribute in python, which returns the name of the current module or function. As we know , python allows us to import one module into another. So we can create different modules for different functionalities. The __name__ is a special attribute contained in every module of python.
__name__ let us know whether we are using an imported module function or function within main module. If the module is running as main program (function is inside main program) then it returns ‘__main__’ otherwise it will return the name of the module in which it exist.
__name__ == ‘__main__’
You may seen __name__ == ‘ __name__’ in different programs. As we discussed earlier, if a module is running as main program then __name will return ‘__main__’ . So we can take advantage of this , by deciding or controlling the accessibility of the function. We can customize the accessibility , according to how it runs whether it is working as main program or imported function.
Sometimes when you are importing a module .You would like to know whether a module function is being used as an import, or if you are using the original .
if __name__ == '__main__'
If module running directly , it returns true . Otherwise it returns file if it is imported into another module.
Unlike another languages , there is no need to define main() . Whole code at indentation level 0 (at top level , with no starting space ) is called main.
Suppose , you want to change the behaviour , accessibility of particular function . You want run it only when it is working as main program , otherwise not if it is being imported.
There are two files
def circle_area(radius): '''Accessible only in main program ''' return 3.14 * radius * radius print('value of __name__ is: '+__name__) if __name__ == '__main__': print('area.py running directly') a = circle_area(10) print("Area of circle is :", a) else: print("area.py has been imported")
import area area.circle_area(10) print("Value of __name__ is: " + __name__ ) if __name__ == '__main__': print('display.py running directly') else: print("display.py has been imported")
In example above, there are two files area.py and display.py . We use attribute __name__ inside both of files. As you can see in the output :
- First i have call area.py , so here variable __name__ returns the ‘__main__’ , prints area.py running directly, and function returns area.
- Secondly , i have call display.py , as shown in input above , inside display.py i have called area.py . So variable __name__ returns name of the module being used i.e. area.
- Also display.py prints that it is running directly.
So that’s all about __name__ in python , i hope you guys enjoyed the article , Thanks!!!