Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pierian-data

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: pierian-data/complete-python-3-bootcamp
Path: blob/master/06-Modules and Packages/01-Name_and_Main/Explanation.txt
Views: 648
1
Sometimes when you are importing from a module, you would like to know whether
2
a modules function is being used as an import, or if you are using the original
3
.py file of that module. In this case we can use the:
4
5
if __name__ == "__main__":
6
7
line to determine this. For example:
8
9
When your script is run by passing it as a command to the Python interpreter:
10
11
python myscript.py
12
13
all of the code that is at indentation level 0 gets executed. Functions and
14
classes that are defined are, well, defined, but none of their code gets ran.
15
Unlike other languages, there's no main() function that gets run automatically
16
- the main() function is implicitly all the code at the top level.
17
18
In this case, the top-level code is an if block. __name__ is a built-in variable
19
which evaluate to the name of the current module. However, if a module is being
20
run directly (as in myscript.py above), then __name__ instead is set to the
21
string "__main__". Thus, you can test whether your script is being run directly
22
or being imported by something else by testing
23
24
if __name__ == "__main__":
25
...
26
27
If that code is being imported into another module, the various function and
28
class definitions will be imported, but the main() code won't get run. As a
29
basic example, consider the following two scripts:
30
31
# file one.py
32
def func():
33
print("func() in one.py")
34
35
print("top-level in one.py")
36
37
if __name__ == "__main__":
38
print("one.py is being run directly")
39
else:
40
print("one.py is being imported into another module")
41
42
and then:
43
44
# file two.py
45
import one
46
47
print("top-level in two.py")
48
one.func()
49
50
if __name__ == "__main__":
51
print("two.py is being run directly")
52
else:
53
print("two.py is being imported into another module")
54
55
Now, if you invoke the interpreter as
56
57
python one.py
58
59
The output will be
60
61
top-level in one.py
62
63
one.py is being run directly
64
If you run two.py instead:
65
66
python two.py
67
68
You get
69
70
top-level in one.py
71
one.py is being imported into another module
72
top-level in two.py
73
func() in one.py
74
two.py is being run directly
75
76
Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.
77
78