Home  >  Article  >  Backend Development  >  How to find the current module name in Python?

How to find the current module name in Python?

WBOY
WBOYforward
2023-08-27 08:41:06910browse

How to find the current module name in Python?

A module can find its own module name by looking at the predefined global variable __name__. If its value is "__main__", the program runs as a script.

Example

def main():
   print('Testing…...')
   ...
if __name__ == '__main__':
   main()

Output

Testing…...

Modules typically used via import also provide a command line interface or self-test, and this code is only executed after checking __name__.

__name__ is a built-in variable in the Python language. We can write a program to view the value of this variable. Here is an example. We will also check the type -

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__

The above is the detailed content of How to find the current module name in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete