On 2017-12-01 22:46, Steven D'Aprano wrote:
On Fri, Dec 01, 2017 at 10:23:37AM -0500, brent bejot wrote:
I have found myself implementing something like this before. I was working on a command-line tool with nested sub-commands. Each sub-command would import a script and execute something out of it. I ended up moving the importing of those little scripts into the functions that called them because importing all of them was slowing things down. A built-in lazy importer would have made for a better solution.
If I understand your use-case, you have a bunch of functions like this:
def spam_subcommand(): import spam spam.command()
def eggs_subcommand(): import eggs eggs.command()
With lazy importing, you might have something like this:
spam = lazy_import('spam') eggs = lazy_import('eggs')
def spam_subcommand(): load(spam) spam.command()
def eggs_subcommand(): load(eggs) eggs.command()
I don't see the benefit for your use-case. How would it be better? Have I missed something?
You don't think you'd need the 'load'; you'd delay execution of the module's code until the first attribute access.
All of the script's module dependencies would be listed at the top, but you could avoid most of the cost of importing a module until you know that you need the module's functionality.