Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I find the current module name in Python?
In Python, every module has a built-in variable __name__ that contains the current module's name. When a script is run directly, __name__ equals '__main__'. When imported as a module, it contains the actual module name.
Basic Usage of __name__
Let's check the value and type of __name__ in a running script:
print(__name__) print(type(__name__))
__main__ <class 'str'>
Using __name__ for Script Entry Point
The most common use is to create code that only runs when the file is executed directly:
def main():
print('Testing...')
print('This runs only when script is executed directly')
if __name__ == '__main__':
main()
Testing... This runs only when script is executed directly
Module Name Detection
Here's a function that demonstrates how __name__ changes based on execution context:
def show_module_info():
print(f'Current module name: {__name__}')
print(f'Is this the main module? {__name__ == "__main__"}')
show_module_info()
if __name__ == '__main__':
print('Running as main script')
else:
print('Running as imported module')
Current module name: __main__ Is this the main module? True Running as main script
Practical Example
This pattern is useful for creating modules that can both be imported and run standalone:
def calculate_area(radius):
"""Calculate circle area"""
return 3.14159 * radius ** 2
def run_tests():
"""Test function for demonstration"""
test_radius = 5
area = calculate_area(test_radius)
print(f'Area of circle with radius {test_radius}: {area}')
# This only runs when script is executed directly
if __name__ == '__main__':
print('Running circle calculator tests...')
run_tests()
Running circle calculator tests... Area of circle with radius 5: 78.53975
Key Benefits
| Usage | __name__ Value | Benefit |
|---|---|---|
| Direct execution | '__main__' | Runs entry point code |
| Imported module | Module name | Prevents unwanted execution |
| Debugging | Identifies context | Helps trace execution flow |
Conclusion
Use __name__ to determine if your script is running directly or being imported. The if __name__ == '__main__': pattern is essential for creating reusable modules with optional standalone functionality.
