How to find the current module name in Python?

WBOY
Release: 2023-08-27 08:41:06
forward
908 people have browsed it

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()
Copy after login

Output

Testing…...
Copy after login

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__))
Copy after login

Output

__main__
<type 'str'>
Copy after login

Example

Let’s see another example -

We have a file Demo.py.

def myFunc():
   print('Value of __name__ = ' + __name__)
if __name__ == '__main__':
   myFunc()
Copy after login

Output

Value of __name__ = __main__
Copy after login

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__)
Copy after login

Output

Running the imported script
Value of __name__ = Demo

Running the current script
Value of __name__ = __main__
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!