Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: 'X' in try block with 'except ImportError' should also be defined in except block

Tags:

python

pycharm

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.

like image 458
V.K. Avatar asked Sep 19 '25 04:09

V.K.


1 Answers

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.

like image 71
newlog Avatar answered Sep 21 '25 19:09

newlog