Browse code

use a try except in _RequireAttrsABCMeta

Bas Nijholt authored on 16/10/2019 22:20:20
Showing 1 changed files
... ...
@@ -74,11 +74,12 @@ class _RequireAttrsABCMeta(abc.ABCMeta):
74 74
     def __call__(self, *args, **kwargs):
75 75
         obj = super().__call__(*args, **kwargs)
76 76
         for name, type_ in obj.__annotations__.items():
77
-            if not hasattr(obj, name):
78
-                raise ValueError(f"Required attribute {name} not set in __init__.")
79
-            elif not isinstance(getattr(obj, name), type_):
80
-                raise TypeError(
81
-                    f"The attribute '{name}' is of {type_} instead of {type(getattr(obj, name))}"
82
-                )
83
-
77
+            try:
78
+                x = getattr(obj, name)
79
+                if not isinstance(x, type_):
80
+                    raise TypeError(
81
+                        f"The attribute '{name}' is of {type_} instead of {type(x)}."
82
+                    )
83
+            except AttributeError as e:
84
+                raise e(f"Required attribute {name} not set in __init__.")
84 85
         return obj