
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do I find the 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__
- Related Articles
- How do I find the location of Python module sources?
- How do I calculate the date six months from the current date using the datetime Python module?
- How do I unload (reload) a Python module?
- How do I disable log messages from the Requests Python module?
- How do I get current URL in Selenium Webdriver 2 Python?
- How do I get the current date in JavaScript?
- How I can dynamically import Python module?
- How do I get the current date and time in JavaScript?
- Where do I find the current C or C++ standard documents?
- How I can install unidecode python module on Linux?
- How do I get the current time zone of MySQL?
- How do I find the largest integer less than x in Python?
- How I can check a Python module version at runtime?
- How can I get the current week using Python?
- How do I get the current AUTO_INCREMENT value for a table in MySQL?

Advertisements