Defer, ensure library is loaded

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 13 19:13:06 EST 2018


On Wed, 14 Feb 2018 03:08:07 +1100, Chris Angelico wrote:

[...]
> import psycopg2
> 
> If it's already been imported, Python will go fetch it straight from the
> cache, so it's fast.

Since Jason is talking about "a variety of scripts", it is quite possible 
that the sys.modules cache will not save him. Consider a scenario of a 
dozen scripts, each importing psycopg2. Since each script runs in its own 
interpreter process, sys.modules is cleared from one run to the next.

For scripts run by hand, this rarely matters. (After all, the time to run 
the script is often less than the time it takes to type in the command to 
run and hit Enter.) But for scripts called by other scripts, this can 
sometimes cause a significant slowdown.

(My understanding is that this is one of the reasons for the Apache 
module "mod_python", to ensure a single Apache process runs a single, 
long-running Python interpreter for any Python scripts, rather than 
starting and stopping a new interpreter like ordinary CGI scripts would 
do.)

I must admit though, I don't really understand Jason's problem or whether 
your answer is even relevant.



-- 
Steve




More information about the Python-list mailing list