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.
None. Sooner or later someone has to deal with this anyway :)
@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!
Most helpful comment
Yes exactly, the specific exception we try to catch.
Also, sometimes we don't need exception handling at all:
can be replaced with
x = getattr(myobject, "attribute", 0)