Skip to content

prevent itf to be an unbound variable in _cominterface_meta.__get_baseinterface_methodcount #472

Closed
@junkmd

Description

@junkmd

Since itf can be an unbound variable, the following code will cause several type checkers to warn.

def __get_baseinterface_methodcount(self):
"Return the number of com methods in the base interfaces"
try:
result = 0
for itf in self.mro()[1:-1]:
result += len(itf.__dict__["_methods_"])
return result
except KeyError as err:
(name,) = err.args
if name == "_methods_":
raise TypeError("baseinterface '%s' has no _methods_" % itf.__name__)
raise

But this try...except... clause traps a KeyError.

Therefore, it is possible to change to a better code by verifying the existence of the key.

-        try:
-            result = 0
-            for itf in self.mro()[1:-1]:
+        result = 0
+        for itf in self.mro()[1:-1]:
+            if "_methods_" in itf.__dict__:
                 result += len(itf.__dict__["_methods_"])
-            return result
-        except KeyError as err:
-            (name,) = err.args
-            if name == "_methods_":
-                raise TypeError("baseinterface '%s' has no _methods_" % itf.__name__)
-            raise
+            else:
+                raise TypeError(f"baseinterface '{itf.__name__}' has no _methods_")
+        return result

Maybe vars(itf) is better than itf.__dict__, or maybe there is another way to write it better, but I'll leave it to the contributors for fixing this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions