importing down in code rather than at top of file.

Terry Reedy tjreedy at udel.edu
Mon Aug 29 20:40:21 EDT 2016


On 8/29/2016 1:57 PM, Tobiah 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?

If you delay the import, you can put it a function, such as 'almost 
never', and then document the delayed import with comments either mixin 
in with or below the real ones, such as

# import large_module  # in almost_never

-- 
Terry Jan Reedy




More information about the Python-list mailing list