Defer, ensure library is loaded
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Feb 13 19:25:25 EST 2018
On Tue, 13 Feb 2018 08:02:38 -0800, Jason wrote:
> I have a variety of scripts that import some large libraries, and rather
> than create a million little scripts with specific imports, I'd like to
> so something like
>
> psycopg2 = ensure_imported (psycopg2)
>
> This way, regardless of invocation I can know psycopg2 is loaded, if it
> hasn't already been loaded. If I just do a normal import 95% of the time
> I'll be waiting time with a meaningless import.
>
>
> Can I do that somehow?
Jason, I'm afraid I don't understand your question. I don't understand
what "ensure_imported" is supposed to do, or how it is different from a
regular import, or where you are supposed to put it.
If you have a "million scripts" that look like this:
# count down from script 1000000 to 1...
import psycopg2
...
# script 999999
import psycopg2
...
# script 999998
import psycopg2
...
etc, how is that different from a million scripts that look like this?
# count down from script 1000000 to 1...
psycopg2 = ensure_imported(psycopg2)
...
Aside from the ensure_imported version being about double as much typing.
Nor do I understand what you mean by having to spend 95% of your time
waiting for a meaningless import. If the import is "meaningless", that
could only possibly mean that you aren't using the imported module. So
the solution to that is to simply *not* import it. You shouldn't start
off every module by importing a bazillion modules that you don't use.
Import only what you actually use.
If you explain your problem a little better, we can possibly help you
solve it.
Oh, one last thing... you cannot write something like this:
foomodule = ensure_imported(foomodule)
because the interpreter has to evaluate the value of the name "foomodule"
on the right hand side of the assignment, and since it hasn't been
imported yet, you will get a NameError. You have to write:
foomodule = ensure_imported("foomodule") # note the quotation marks
to have it work.
--
Steve
More information about the Python-list
mailing list