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 bar
from importing alpha
without hacking around in its source. But you can "fake out" alpha
, by writing it into sys.modules
:
>>> import alpha
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named alpha
>>> import sys; sys.modules['alpha'] = object()
>>> import alpha
>>>
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. Adding alpha
to it means that Python thinks you have already imported alpha
, so when bar
tries to do so it will just get back the cached copy.
Obviously, you should think carefully about whether you are comfortable doing this -- bar
will crash in unexpected ways if it actually uses alpha
anywhere.