importing down in code rather than at top of file.

dieter dieter at handshake.de
Tue Aug 30 03:13:55 EDT 2016


Tobiah <toby at tobiah.org> writes:

> 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 have used delayed import for different reasons:

 * to avoid cyclical imports

 * to avoid import deadlocks in multi-tasking programs
   (Python 2 (at least) used to protect the import machinery with
   a lock; which under some conditions could lead to deadlocks
   in a multi-tasking program).

Typically, the delayed import was then in a function - relying
on the fact that importing an already imported module is fast
(thus, we do not lose much even if the function is called multiple times).




More information about the Python-list mailing list