简体   繁体   中英

How to use alias of a long python module package without really importing it?

I need to import several modules from a long name module path:

import a.b.c.d.m1 as m1
import a.b.c.d.m2 as m2
import a.b.c.d.m3 as m3

I can write the long name only once, like this:

import a.b.c.d as d
m1 = d.m1
m2 = d.m2
m3 = d.m3

But in this way, the package d is fully imported, which I do not want.

Is there a way that just use something to 'remember' the module path, without really import it. Therefore, later we can easily import its sub modules.

alias d = a.b.c.d
from d import m1
from d import m2
from d import m3

From the part that I have perceived from your question, it seems that you need something like this:

from abcd import m1,m2,m3

Why to use complicated stuff when commas can do the job?

Hmm, what to mean by

the package d is fully imported, which I do not want

When you execute

from a.b.c.d import m1

The import machinery does import all the parent packages, meaning here a , ab , abc , abcd , adds them to the sys.module cache and only adds m1 to your global variables list.

So if you write:

from a.b.c import d
from d import m1

you import the same packages and only add a d reference to your global variable list, when you compare to the previous case.

So the alias machinery that you want is not included in the language simply because it was not felt useful enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM