3 ms·
If the file gets executed as a script, then __name__ == "__main__", hence L43:53 get executed in the top-level scope, which is also available in the lower level
by y7 9y ago
If the file gets executed as a script, then __name__ == "__main__", hence L43:53 get executed in the top-level scope, which is also available in the lower levels. This isn't very good writing, since this code will throw exceptions when __name__ != "__main__" (i.e. when import-ing the file as a module), which misleadingly defeats the purpose of having that conditional there.
- zeptomu 9y agoOk, thanks, that makes sense. I knew that top-level variables are global, but didn't know that variables in __main__ share this property (which is e.g. different in the C language).
- AlecSchueler 9y agoif __name__ == __main__ is just a conditional on the top level scope.
- apenwarr 9y agoUsually people write an actual function called main(), and call it from the global level conditional, to avoid this oddness. The actual function called main() has no special meaning in python.