2

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.

solopiu
  • 718
  • 1
  • 9
  • 28
  • What have you tried so far, what what about what you tried doesn't work? – Sylvester Kruin Feb 08 '22 at 17:16
  • 1
    https://stackoverflow.com/questions/3131217/error-handling-when-importing-modules – Andrew Ryan Feb 08 '22 at 17:19
  • @MichaelSzczesny yes, I can’t modify external_library. I could rewrite it ofc but it’s not a good solution imo. The “problem” is that in this library many packages are installed and used in functions that I don’t care about. One of this packages throws an error, but, in general, I don’t like importing a package that I don’t need (need to save space, time) – solopiu Feb 08 '22 at 17:32
  • @SylvesterKruin I’m reading importlib documentation without any success – solopiu Feb 08 '22 at 17:33
  • https://stackoverflow.com/questions/40198924/handling-imported-module-exceptions – Andrew Ryan Feb 08 '22 at 17:35
  • @AndrewRyan I don't want to throw an exception, I want to skip the import if the package name is "package_with_problem". – solopiu Feb 08 '22 at 17:48

2 Answers2

1

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • But in this way the external_library is not imported at all. This only avoid raising the error message – solopiu Feb 09 '22 at 14:27
0

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.

solopiu
  • 718
  • 1
  • 9
  • 28