Intor

__name__ is one such special variable. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value __main__. If this file is being imported from another module, __name__ will be set to the module’s name.
__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement

Using

As main srcipt

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-07-21 12:59:29
# @Author : Simon (simon.xie@codewalker.meg)
# @Link : http://www.codewalker.me
# @Version : 1.0.0
# @filename: first_module.py

if __name__ == "__main__":
print(f'Run first as {__name__}')
else:
print(f'Run first as Import {__name__}')

As a module

Import first_module.py module as a module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-07-21 13:00:31
# @Author : Simon (simon.xie@codewalker.meg)
# @Link : http://www.codewalker.me
# @Version : 1.0.0
# @Filename: second_module.py

import first_module

def second_main():
print(f'Run second as {__name__}')
if __name__ == "__main__":
second_main()

See what’s the different of __name__

Round one

We run first_module.py directly, it will show us Run first as __main__, because we check the value of __name__. Obvisously it’s.

Round two

Running second_module.py. it shows us Run first as Import first_module. Here, we’ve known the value of __name__ will be changed. At first script it’s value is ‘main‘ as main level, but it has changed to module name when we import it as a module.

EOF.