haofeng
haofeng

Reputation: 651

How to use python alias module name import child module?

For example:

I want the below-given syntax to change to two lines.

from A.B import C

->

from A import B
from B import C # I want **B is a child module of A** in this line

Why do I need this change?

Because I got an open-source project based on Keras, not tensorflow.keras, and I need to change all keras to tensorflow.keras by doing the change to save time, instead of adding tensorflow. in front of keras in all files.

from tensorflow.keras import optimizers

->

from tensorflow import keras
from keras import optimizers # **keras is child moudle of tensorflow** in this line

Is the change possible ?

Upvotes: 1

Views: 172

Answers (1)

Vincent Bénet
Vincent Bénet

Reputation: 1314

You can add multiple modules and rename them using:

from A.B import C, D as E, F
from G.H import C, D as I, J

in your specific case, it gives:

from tensorflow.keras import optimizers as optimizers1
from keras import optimizers as optimizers2

Then you can use them in python code like this:

optimizers1.func1()
optimizers2.func2()

Upvotes: 2

Related Questions