From b31539f62e60e1ad370214e05003c214298d2431 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Pr=C3=A6sius?= Date: Fri, 23 Aug 2019 14:21:39 +0200 Subject: [PATCH] Guard against AttributeError in dataloaders. (#161) A solution for https://github.com/williamFalcon/pytorch-lightning/issues/142. Since hasattr "calls getattr(object, name) and to see whether it raises an AttributeError or not", I replaced it with a single call to getattr. See also https://stackoverflow.com/questions/24971061/python-hasattr-vs-getattr --- pytorch_lightning/root_module/decorators.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pytorch_lightning/root_module/decorators.py b/pytorch_lightning/root_module/decorators.py index ef7bd50283..f295be0cb0 100644 --- a/pytorch_lightning/root_module/decorators.py +++ b/pytorch_lightning/root_module/decorators.py @@ -10,8 +10,15 @@ def data_loader(fn): @property def _data_loader(self): - if not hasattr(self, attr_name): - setattr(self, attr_name, fn(self)) - return getattr(self, attr_name) + try: + value = getattr(self, attr_name) + except AttributeError: + try: + value = fn(self) # Lazy evaluation, done only once. + except AttributeError as e: + # Guard against AttributeError suppression. (Issue #142) + raise RuntimeError('An AttributeError was encountered: ' + str(e)) from e + setattr(self, attr_name, value) # Memoize evaluation. + return value return _data_loader