Re:Ask HN: Good Python projects to read for modern Python?
by roveo on Monday December 27, 2021 @07:02AM
(#29701777)
What's up with
if __name__ == "__main__": some random code
at the end of module files? Never seen that, why is it used? I understand that it's a guard that only runs when the module is executed directly, but what is the code put there? For developers to quickly visually test stuff by running the module?Here, for example https://github.com/willmcgugan/rich/blob/master/rich/color.p...
Re:Ask HN: Good Python projects to read for modern Python?
by npage97 on Monday December 27, 2021 @08:19AM
(#29702249)
Yea it is there for devs to see different rich features in their console.
You can run some examples using the -m flag + the submodule:
python -m rich.live
python -m rich.markdown # this is actually a markdown to terminal cli
https://rich.readthedocs.io/en/stable/live.html
https://rich.readthedocs.io/en/stable/markdown.html
Re:Ask HN: Good Python projects to read for modern Python?
by FreakLegion on Monday December 27, 2021 @03:21PM
(#29706361)
It's a common pattern as others have said, but this specific version of it is poor practice. The code should be in a function instead of polluting the global namespace (otherwise 'console', 'table', and 'color' end up being shadowed if they're used elsewhere in the file). Keep it clean with e.g.:
def main() -> None:
pass
if __name__ == "__main__":
main()
Re:Ask HN: Good Python projects to read for modern Python?
by willm on Monday December 27, 2021 @05:35PM
(#29707677)
That is not the case. The code within that block will not be in the namespace if that file is imported. Contrary to your example which will have the main function in the module namespace.
Re:Ask HN: Good Python projects to read for modern Python?
by FreakLegion on Tuesday December 28, 2021 @01:56AM
(#29711212)
> "if that file is imported"
Static analysis doesn't care. The script can be executed directly, so it has to be treated as if it will be. The fact that the code behaves differently between prod and dev use is a smell, not a selling point.
I'm saying this in the context of writing modern Python with modern tools. In that context it's a poor practice.
I found Will’s codebase easy to read and reason about, making it easy to help extend.