Reputation: 756
What I'd like to do is avoid an import that cause a problem. My code is like this:
main.py
import external_library
external_library.py
import package_with_problem
I know I could change external_library.py
with something as
try:
import package_with_problem
except:
pass
but I'm looking for a solution to implement in main.py
. I would like a skip function that takes the package name as parameters and avoid the import.
Upvotes: 2
Views: 1591
Reputation: 19430
Just do in main.py
the same as you would have in external_library.py
. If you only want to skip a certain import, you can check the error:
try:
import external_library
except ImportError as e:
if "package_with_problem" not in e.msg:
raise
This will "skip" the import of package_with_problem
but will re-raise the error for any other package.
Upvotes: 1
Reputation: 756
I found a workaround, I believe it exists a better way to do this but anyway, this is my possible solution for now.
Create a new empty file.
new_empty_file.py
# nothing or print("Hello") to see something in output
main.py
import new_empty_file
import sys
sys.modules['package_with_problem'] = new_empty_file
import external_library # this should use package_with_problem in cache that is new_empty_file
If the import in external library has some subpackage, create a new function called as subpackage in new_empty_file as:
new_empty_file.py
def subpackage():
return
Unfortunately, it is necessary to have package_with_problem
in sys and installed, so, not a good solution, it only avoid importing the real library.
Upvotes: 0