Kurt Bourbaki
Kurt Bourbaki

Reputation: 12596

Importing functions from module with dependencies without raising ImportErrors

I have a package called analysis.

When I import this package (with the command from app import analysis) I get an ImportError exception because of a missing library that should be imported in another package (web_package).

I want to be able to import analysis even if I do not have that library installed, because analysis is only importing functions from web_package that can work even without the library.

analysis/__init__.py:

from app.analysis.util import some_function

analysis/util.py :

from app.web_package.util import some_other_function

web_package/__init__.py :

from app.web_package.web_client import SomeClass

web_package/web_client.py :

from missing_library import ParentClass

def SomeClass(ParentClass):

At this point what can I do if I do not have missing_library installed, but I still want to use some functions from web_package/util.py? Whenever I try to import something from app.web_package.util it automatically goes into web_package/__init__.py and then in web_client.py, that causes an ImportError to be raised. What can I do?

Wrapping from missing_library import ParentClass into a try/except block will cause an error with def SomeClass(ParentClass).

Upvotes: 1

Views: 632

Answers (2)

Gerard van Helden
Gerard van Helden

Reputation: 1602

You could define a stub in an except clause. The following works:

try:
   from foo import bar;
except:
   class foo:
      pass

class baz(foo):
   pass

It is pretty bad design, though, imho, but that's fairly opinionated.

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90899

I would say the easiest way to go would be to refactor your code into two different modules.

One module has the missing_library import and only has code that depends on this missing_library like SomeClass , then the other module has the functions, that you want to use, that are not dependent on the missing library.

Then if you want to use some of those independent functions in your dependent module, you can simply import that module in it.

Then in your __init__.py , you can put the try/except Example -

try:
    from app.web_package.web_client import SomeClass
except ImportError:
    pass                                #Or import some other version of `SomeClass` ?

Upvotes: 1

Related Questions