[Python] Is "if __name__ == '__main__'" required in a __main__.py?

Discussão em 'Python' iniciado por Stack, Junho 9, 2025.

  1. Stack

    Stack Membro Participativo

    In a project that has a __main__.py, rather than

    # __main__.py
    # def main...

    if __name__ == "__main__":
    main()


    ...is it OK to just do:

    # __main__.py
    # def main...

    main()


    Edit:

    @user2357112-supports-Monica's argument made a lot of sense to me, so I went back and tracked down the library that had been giving me issues, causing me to still be adding the if __... line. It's upon calling python -m pytest --doctest-modules.

    Maybe that's the only place that makes a mistake in running __main__.py? And maybe that's a bug?

    Reproduced by putting the first example in the docs in a __main__.py:

    ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― package/__main__.py ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
    package/__main__.py:58: in <module>
    args = parser.parse_args()
    /usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py:1755: in parse_args
    args, argv = self.parse_known_args(args, namespace)
    /usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py:1787: in parse_known_args
    namespace, args = self._parse_known_args(args, namespace)
    /usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py:2022: in _parse_known_args
    ', '.join(required_actions))
    /usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py:2508: in error
    self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
    /usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py:2495: in exit
    _sys.exit(status)
    E SystemExit: 2
    --------------------------------------------------------------------------------------- Captured stderr ---------------------------------------------------------------------------------------
    usage: pytest.py [-h] [--sum] N [N ...]
    pytest.py: error: the following arguments are required: N

    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    Results (4.23s):

    Continue reading...

Compartilhe esta Página