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__

Updated on: 20-Sep-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements