Skip to content

Type checkers issues a warning when unpacking elements of _fields_. #663

@junkmd

Description

@junkmd

The following is pointed in python/typeshed#12982 (comment).

I did a local comparison using mypy --strict and there were only two things that meaningfully changed, both additional findings:

> comtypes/_memberspec.py:191: error: "type[_CData]" has no attribute "from_param"  [attr-defined]
> comtypes/test/find_memleak.py:26: error: Too many values to unpack (2 expected, 3 provided)  [misc]

The second is from a line like this:

for n, _ in self._fields_:

This is also a correct addition. _fields_ is typically a list of 2-tuples, and on the class in question within comtypes that's true, but in the general case it's valid for _fields_ to include 3-tuples (c.f. https://docs.python.org/3/library/ctypes.html#ctypes.Structure._fields_). It's safe because your class doesn't use any 3-tuple fields, but I don't think there's anything that could be done in the stubs that would allow mypy to realize that.

Therefore, the following would be changed as shown.

from comtypes.util import cast_field
result = type(self)()
for n, _ in self._fields_:
setattr(result, n, getattr(self, n))
url, title = self.pwcsUrl, self.pwcsTitle
windll.ole32.CoTaskMemFree(cast_field(self, "pwcsUrl", c_void_p))

         from comtypes.util import cast_field

         result = type(self)()
-        for n, _ in self._fields_:
+        for n, *_ in self._fields_:
             setattr(result, n, getattr(self, n))
         url, title = self.pwcsUrl, self.pwcsTitle
         windll.ole32.CoTaskMemFree(cast_field(self, "pwcsUrl", c_void_p))

Additionally, similar code exists elsewhere, and pyright in my environment was issuing warnings about it. This would be changed as well.

self.cb = sizeof(self)
def dump(self):
for n, _ in self._fields_[2:]:
print(n, getattr(self, n) / 1e6)

         self.cb = sizeof(self)
 
     def dump(self):
-        for n, _ in self._fields_[2:]:
+        for n, *_ in self._fields_[2:]:
             print(n, getattr(self, n) / 1e6)

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueGood for newcomerstypingrelated to Python static typing system

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions