importlib
can help here
import importlib
from A import B
importlib.import_module('A.B.C')
importlib.import_module('A.B.D')
# Now you can use B.C & B.D
On Python2.6 you should be able to
from A import B
import A.B.C
import A.B.D
del A
سؤال
In Python, it is possible to import dotted submodules explicitly:
import os.path
makes os.path
available.
Now, is there a simple way to do the same thing for sub-submodules? The following code (which does not work) illustrates what I am looking for:
from A import B.C
from A import B.D
(from A import B
does not import B.C
and B.D
, for the module A.B
that I need to use). I would like to do this because:
C
and D
(from A.B import C, D
) because they do not have very specific names.B
namespace (for the same reason).One solution is to do:
from A import B
from A.B import C, D
del C, D
which loads and defines B.C
and B.D
. However, this is (1) quite unusual, (2) somewhat obscure (side effect of defining B.C
and B.D
) and (3) maybe with a result that's not guaranteed (will B.C
and B.D
always be defined with this code?).
Is this method of putting only B.C
and B.D
(and B
) in the namespace acceptable? is there a better method? maybe it actually best to find some legible compromise like from A.B import C as B_C, D as B_D
?
While I am stuck with Python 2.6 (no importlib module…), for this problem, I am also curious about any modern solution.
المحلول 2
importlib
can help here
import importlib
from A import B
importlib.import_module('A.B.C')
importlib.import_module('A.B.D')
# Now you can use B.C & B.D
On Python2.6 you should be able to
from A import B
import A.B.C
import A.B.D
del A
نصائح أخرى
For the intent of from A import B.C
, I would suggest doing this:
from A.B import C as B_C
One of the cleanest ways is to do what Jayanth mentioned. If A
is a long name then you can rename using the 'as' keyword
import A as X