argparse with subcommands generally requires specifying all of the options for all of the subcommands, even if you only want one subcommand.
These in turn may require importing subcommand-specific modules, to handle things like the right 'type' handler in an an add_argument() parameter. This callback function might, depending on the input value, select one from a dozen different additional packages.
It's possible to avoid this, by deferring argument->type processing until later, and having a single large module containing all of the help strings and epilogs, though this will separate your argparse code from your subcommand code, and in general make things more complicated. I did this for a while.
Alternatively, you can create your own subcommand dispatch system using an nargs="?" to get the subcommand and an nargs=argparse.REMAINDER to capture the rest of the flags, to pass to a new ArgumentParser, and develop a top-level --help replacements. I tried this too.
I've since decided to use click, which does a better job at compartmentalizing at least this level of subcommand imports.
mylib = None
in the global scope and then
global mylib
if mylib is None:
import mylib
in your function to avoid the extra function call.E.g first the local dict, then the global and then the modules dict, instead of just the global+modules
import mod
is the equivalent of
mod = sys.modules.get(name)
if not mod:
mod = sys.modules[name] = load_package(name)
It’s really low cost, as long as you’re not doing it in a hot loop, it’ll be very low to no impact.