[Python-ideas] Provide a way to import module without exec body

Steven D'Aprano steve at pearwood.info
Fri Dec 1 17:46:48 EST 2017


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?


-- 
Steve


More information about the Python-ideas mailing list