__name__ __main__

suggest change

The special variable __name__ is not set by the user. It is mostly used to check whether or not the module is being run by itself or run because an import was performed. To avoid your module to run certain parts of its code when it gets imported, check if __name__ == '__main__'.

Let module_1.py be just one line long:

import module2.py

And let’s see what happens, depending on module2.py

Situation 1

module2.py

print('hello')

Running module1.py will print hello

Running module2.py will print hello

Situation 2

module2.py

if __name__ == '__main__':
    print('hello')

Running module1.py will print nothing

Running module2.py will print hello

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


The __name__ special variable:
* __name__ __main__

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
50 The __name__ special variable
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve