How can I import a python class but avoid running the import statement in that module?
Module foo
from bar import A
Module bar
import alpha
class A(object):
...
class B(objects):
...
I want to import class A but don’t need class B. The import statement in the module bar is required for class B but I’d like to avoid needing to install that dependency if possible, as (I assume) it will be loaded into memory but not used.
Any help would be appreciated.
You can’t stop
barfrom importingalphawithout hacking around in its source. But you can “fake out”alpha, by writing it intosys.modules:This works because Python caches imported modules in
sys.modules, so that if you import something twice you don’t have to go through all the hard work the second time. Addingalphato it means that Python thinks you have already importedalpha, so whenbartries to do so it will just get back the cached copy.Obviously, you should think carefully about whether you are comfortable doing this —
barwill crash in unexpected ways if it actually usesalphaanywhere.