4

I am trying to write a wrapper around two similar libraries which would give me a common API to both of them. Example:

# file XY.version.py
try:
    import X  # primary library
    __version__ = X.__version__
except ImportError:
    import Y  # fallback library
    __version__ = Y.__y_version__

PyCharm shows warning "'X' in try block with 'except ImportError' should also be defined in except block". Is there any simple way to restructure code to get rid of the message? Of course I could do X = None at the very beginning or in the except block but this feels artificial since I only need to import X in order to get the version. Ideally I do not want to keep traces of the import in the namespace. Of course I could theoretically do del X at the end of the try block but this is something I have not seen anywhere so I assume people do not use it and btw. it does not remove the warning message in PyCharm.

Note: I know this is similar to Checking module name inside 'except ImportError' but I believe this is not the same.

Community
  • 1
  • 1

2 Answers2

3

What about something along the lines:

# file XY.version.py 
try:
  import X  # primary library
  __version__ = X.__version__ 
except ImportError:
  import Y as X # fallback library
  __version__ = X.__y_version__

Then use X everywhere.

newlog
  • 1,050
  • 1
  • 11
  • 23
0

I cant see any answers that give a solution to this but check this link: https://pythonbasics.org/try-except/

Gives a clue to whats needed with the list of exceptions and meanings. So if you want to just get rid of the annoying message then add to the exception like so:

try:
    import X  # primary library
    __version__ = X.__version__
except ImportError(X):
    import Y  # fallback library
    __version__ = Y.__y_version__

Works for me in a similar example and does not seem to affect the outcome. I'm using Pycharm 2021.1 CE