importing down in code rather than at top of file.

Chris Angelico rosuav at gmail.com
Mon Aug 29 14:15:05 EDT 2016


On Tue, Aug 30, 2016 at 3:57 AM, Tobiah <toby at tobiah.org> wrote:
> Is it  worth while to defer the import of a large module that seldom
> gets used in the script?
>
>
>         import sys
>         import os
>
>         if hardly_ever_happens():
>
>                 import large_module
>                 large_module.do_task()
>
>
>
> I imagine it takes a certain amount of processing
> power and memory to import a module, so it seems
> like I'd save those resources with the above pattern.
>
> The down side would be that it's nice to see all of the
> imports at the top which would follow convention.  Should
> I care?

Don't imagine; test. Time your program with and without a top-of-file
import. If the module really is large (and by "large" I mean on the
scale of numpy - huge stuff), then yes, it's worth it. If you can't
measure the difference, though, don't bother - just import it and have
done with it.

ChrisA



More information about the Python-list mailing list