Skip to content

Commit 8ab7823

Browse files
committed
shorten the __name__ __main__ embed
1 parent 6fbba63 commit 8ab7823

1 file changed

Lines changed: 10 additions & 18 deletions

File tree

bot/resources/tags/if-name-main.md

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,20 @@
11
---
22
embed:
3-
title: "`if __name__ == '__main__'`"
3+
title: "`if __name__ == "__main__"`"
44
---
5-
This is a statement that is only true if the module (your source code) it appears in is being run directly, as opposed to being imported into another module. When you run your module, the `__name__` special variable is automatically set to the string `'__main__'`. Conversely, when you import that same module into a different one, and run that, `__name__` is instead set to the filename of your module minus the `.py` extension.
65

7-
**Example**
8-
```py
9-
# foo.py
10-
11-
print('spam')
6+
This is a convention for code that should run if the file is the main file of your program:
127

13-
if __name__ == '__main__':
14-
print('eggs')
15-
```
16-
If you run the above module `foo.py` directly, both `'spam'`and `'eggs'` will be printed. Now consider this next example:
178
```py
18-
# bar.py
9+
def main():
10+
...
1911

20-
import foo
12+
if __name__ == "__main__":
13+
main()
2114
```
22-
If you run this module named `bar.py`, it will execute the code in `foo.py`. First it will print `'spam'`, and then the `if` statement will fail, because `__name__` will now be the string `'foo'`.
2315

24-
**Why would I do this?**
16+
If the file is run directly, then the `main()` function will be run.
17+
If the file is imported, it will not run.
2518

26-
- Your module is a library, but also has a special case where it can be run directly
27-
- Your module is a library and you want to safeguard it against people running it directly (like what `pip` does)
28-
- Your module is the main program, but has unit tests and the testing framework works by importing your module, and you want to avoid having your main code run during the test
19+
For more about why you would do this and how it works, see
20+
[`if __name__ == "__main__"`](https://pythondiscord.com/pages/guides/pydis-guides/if-name-main/).

0 commit comments

Comments
 (0)