Pytorch-lightning: Improve Exception Handling

Created on 19 Jun 2020  ·  6Comments  ·  Source: PyTorchLightning/pytorch-lightning

🚀 Code Quality Improvement

I came across this a few times already:

try:
   # something
except Exception:
   # something

It is the worst possible way to handle Exceptions. It is better to catch the specific exception or at least log a message.

Alternatives

None. Sooner or later someone has to deal with this anyway :)

Hacktoberfest Priority P2 enhancement good first issue help wanted let's do it!

Most helpful comment

Yes exactly, the specific exception we try to catch.
Also, sometimes we don't need exception handling at all:

try: 
    x = myobject.attribute
except Exception
    x = 0

can be replaced with
x = getattr(myobject, "attribute", 0)

All 6 comments

@awaelchli so what do you propose to have more exact Exceptions like ImportError?

Yes exactly, the specific exception we try to catch.
Also, sometimes we don't need exception handling at all:

try: 
    x = myobject.attribute
except Exception
    x = 0

can be replaced with
x = getattr(myobject, "attribute", 0)

Another code smell we frequently see (in many places in the code):

try:
    from some_package import some_module
except ImportError:
    SOMEPACKAGE_AVAILABLE = False
else:
    SOMEPACKAGE_AVAILABLE = True

Better:

catch ModuleNotFoundError instead

Even better (and shorter):

import importlib
SOMEPACKAGE_AVAILABLE = importlib.util.find_spec("some_package") is not None

About the import error, I remember that thare is something twisted about python version and avalanche exceptions, I guess that py3.6 doesn't have the one suggest (need to check)

Also is there a simple way how to import jist a function from a package that you are not sure if it is installed?

Also is there a simple way how to import jist a function from a package that you are not sure if it is installed?

I think the simplest is this:

if importlib.util.find_spec("some_package") is not None:
    from some_package import my_function

because when we import the function in Python it always has to import the whole package anyway.

This issue has been automatically marked as stale because it hasn't had any recent activity. This issue will be closed in 7 days if no further activity occurs. Thank you for your contributions, Pytorch Lightning Team!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

edenlightning picture edenlightning  ·  3Comments

jcreinhold picture jcreinhold  ·  3Comments

chuong98 picture chuong98  ·  3Comments

williamFalcon picture williamFalcon  ·  3Comments

as754770178 picture as754770178  ·  3Comments