
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Current Module Name in Python
A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script.
Example
def main(): print('Testing?...') ... if __name__ == '__main__': main()
Output
Testing?...
Modules that are usually used by importing them also provide a command-line interface or a selftest, and only execute this code after checking __name__.
The__name__ is an in-built variable in python language, we can write a program just to see the value of this variable. Here's an example. We will check the type also ?
Example
print(__name__) print(type(__name__))
Output
__main__ <type 'str'>
Example
Let's see another example -
We have a file Demo.py.
def myFunc(): print('Value of __name__ = ' + __name__) if __name__ == '__main__': myFunc()
Output
Value of __name__ = __main__
Example
Now, we will create a new file Demo2.py. In this we have imported Demo and called the function from Demo.py.
import Demo as dm print('Running the imported script') dm.myFunc() print('\n') print('Running the current script') print('Value of __name__ = ' + __name__)
Output
Running the imported script Value of __name__ = Demo Running the current script Value of __name__ = __main__
Advertisements