[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

def eggs_subcommand():
    import eggs

With lazy importing, you might have something like this:

spam = lazy_import('spam')
eggs = lazy_import('eggs')

def spam_subcommand():

def eggs_subcommand():

I don't see the benefit for your use-case. How would it be better? Have 
I missed something?


More information about the Python-ideas mailing list