logoalt Hacker News

mr_mitmyesterday at 7:24 AM1 replyview on HN

You don't have to import everything just to print the help. I try to avoid top-level imports until after the CLI arguments have been parsed, so the only import until then is `argparse` or `click`. This way, startup appears to be instant even in Python.

Example:

    if __name__ == "__main__":
        from myapp.cli import parse_args

        args = parse_args()

        # The program will exit here if `-h` is given

        # Now do the heavy imports

        from myapp.lib import run_app

        run_app(args)

Replies

mikepurvisyesterday at 7:39 PM

Another pattern, though, is that a top level tool uses pkg_resources and entry_points to move its core functionality out to verb plugins— in that case the help is actually the worst case scenario because not only do we have to scan the filesystem looking for what plugins are available, they all have to be imported in order to ask each for its help strings.

An extreme version of this is the colcon build tool for ROS 2 workspaces:

https://github.com/colcon/colcon-core/blob/master/setup.cfg#...

Unsurprisingly, startup time for this is not great.