Understanding Python's __name__ Variable: Purpose, Values, and Practical Examples
This article explains the built‑in __name__ variable in Python, how its value differs when a script is run directly versus imported as a module, and demonstrates both scenarios with clear code examples and visual diagrams.
Python developers often encounter the built‑in __name__ variable, typically used in a conditional like if __name__ == '__main__': to control script execution. This article walks through the purpose of __name__ , the values it can take, and how to leverage it for modular code reuse.
What does __name__ do? It is a special attribute present in every Python module. Its value depends on how the module is executed: when the file is run as the main program, __name__ equals the string '__main__' ; when the file is imported, __name__ is set to the module’s filename (without the .py extension).
Possible values of __name__
• Direct execution: __name__ == '__main__' . • Imported as a module: __name__ == 'module_name' .
Case 1 – Running a script directly
Consider nameScript.py containing:
def myFunction():
print('Variable __name__ is ' + __name__)
def main():
myFunction()
if __name__ == '__main__':
main()When executed, Python first sets __name__ to '__main__' , defines the functions, evaluates the if statement as true, and calls main() , which in turn calls myFunction() and prints '__main__' .
Case 2 – Importing the script as a module
Another script importingScript.py imports nameScript.py :
import nameScript as ns
ns.myFunction()During import, Python sets nameScript.py 's __name__ to 'nameScript' . The if __name__ == '__main__' block evaluates to false, so main() is not called. After import, importingScript.py can call ns.myFunction() , which prints the module’s __name__ value 'nameScript' .
Summary
The article demonstrated how the __name__ variable behaves differently when a Python file is executed directly versus when it is imported, allowing developers to write modules that can both provide reusable functionality and act as standalone scripts.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.