Skip to content Skip to sidebar Skip to footer

How Do I Change The Name Of An Imported Library?

I am using jython with a third party application. The third party application has some builtin libraries foo. To do some (unit) testing we want to run some code outside of the appl

Solution 1:

As others have remarked, it is such a plain thing in Python that the import statement iself has a syntax for that:

from foo import foo as original_foo, for example - or even import foo as module_foo

Interesting to note is that the import statemente binds a name to the imported module or object ont he local context - however, the dictionary sys.modules (on the moduels sys of course), is a live reference to all imported modules, using their names as a key. This mechanism plays a key role in avoding that Python re-reads and re-executes and already imported module , when running (that is, if various of yoru modules or sub-modules import the samefoo` module, it is just read once -- the subsequent imports use the reference stored in sys.modules).

And -- besides the "import...as" syntax, modules in Python are just another object: you can assign any other name to them in run time.

So, the following code would also work perfectly for you:

importfoooriginal_foo= foo
classfoo(Mock):
   ...

Post a Comment for "How Do I Change The Name Of An Imported Library?"