Skip to content

Better VT_RECORD type checking and Structure / Union parsing - #994

Merged
junkmd merged 14 commits into
enthought:mainfrom
junkmd:supports_record_info
Nov 14, 2026
Merged

junkmd merged 14 commits into
enthought:mainfrom
junkmd:supports_record_info

Conversation

@junkmd

@junkmd junkmd commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator

Summary

Add new runtime-checkable SupportsRecordInfo ABC and replace isinstance(x, Structure) and hasattr(x, "_recordinfo_") with isinstance(x, SupportsRecordInfo).

Also fix tlbparser.py to pass recordinfo to Structure constructor (prevent incompletely initialized objects from existing after creation) and codegenerator/heads.py to check _recordinfo_ is not None instead of hasattr.
Additionally, refactor typedesc.Structure and typedesc.Union to initialize members list and provide add_member in the shared base class _Struct_Union_Base, eliminating the anti-pattern of passing an external list to the constructor and mutating it later.

Why

The old pattern had three problems:

  1. Instance attribute bug: hasattr returns True for instance attributes. A user could set obj._recordinfo_ = ... on an instance and break things.
  2. No validation: The old code did not check if _recordinfo_ is a valid 5-tuple.
  3. Incompletely initialized objects in parser: tlbparser.py created a Structure, registered it, then set _recordinfo_ later. This allowed incompletely initialized objects to exist. Additionally, the Structure / Union constructors accepted a members list parameter, which was then mutated after construction. This side-effect-based pattern is error-prone.

Trade-offs: dedicated ABC symbol for type checking

Pros: Single source of truth, prevents instance-attribute bug, validates format, cleaner call sites, prevents incompletely initialized objects.
Cons: Metaclass is harder to read; cannot inherit from SupportsRecordInfo (by design).

Justification

Complexity stays in one file (recordinfo.py). All call sites become simpler. Type checkers understand isinstance better than hasattr. Eliminates room for bugs.

Changes

  • recordinfo.py: New SupportsRecordInfo abstract marker class with a custom metaclass. It validates that _recordinfo_ is a class attribute (not instance) and has the correct 5-tuple format.
  • _automation.py, safearray.py: Use isinstance(x, SupportsRecordInfo).
  • tlbparser.py: Pass recordinfo=guids to Structure constructor. The object is fully initialized before registration. Also use add_member for Structure/Union instead of mutating an external list.
  • typedesc_base.py: Make _recordinfo_ optional in Structure constructor. Move members list initialization and add_member method to _Struct_Union_Base base class.
  • codegenerator/heads.py: Check _recordinfo_ is not None instead of hasattr.
  • test_recordinfo.py: Add tests for the new class.
  • test_packing.py: Update tests to use new add_member API.
  • .gitignore: Add C++ test server build artifacts.

…dinfo_` attribute

The old `hasattr(value, "_recordinfo_")` check only verified the attribute exists.
This was unsafe because:
- Instance attributes passed (should be class attribute only)
- Wrong tuple length or element types passed
- Non-Structure types (Union, plain classes) passed

The new `SupportsRecordInfo` class uses a custom metaclass to validate at
class definition time that:
1. The class is a `ctypes.Structure` subclass
2. `_recordinfo_` is a class attribute (not instance attribute)
3. `_recordinfo_` is a valid 5-tuple: (type library GUID string, major
   version, minor version, locale ID, typeinfo GUID string)

`SupportsRecordInfo` works as a protocol like `isinstance(obj, collections.abc...)`
for readability and robust static type analysis.
It is usable only as a type-checking symbol (no inheritance,
subclassing, or instantiation), which is a justified trade-off for
introducing metaprogramming.
…ypedesc.Union` constructors, and add members using `add_member` method.
@junkmd junkmd added this to the 1.5.1 milestone Nov 14, 2026
@junkmd junkmd added enhancement New feature or request typing related to Python static typing system coding style Topics related to style, formatters, linters, and delinting. labels Nov 14, 2026
@codecov-commenter

codecov-commenter commented Nov 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.79412% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.73%. Comparing base (fa5831f) to head (c5c3151).

Files with missing lines Patch % Lines
comtypes/tools/tlbparser.py 85.71% 2 Missing ⚠️
comtypes/safearray.py 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #994      +/-   ##
==========================================
+ Coverage   91.67%   91.73%   +0.06%     
==========================================
  Files         149      149              
  Lines       15281    15357      +76     
==========================================
+ Hits        14009    14088      +79     
+ Misses       1272     1269       -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…tTrue` and `assertFalse` for `SupportsRecordInfo` checks.
@junkmd
junkmd merged commit 1e87ca6 into enthought:main Nov 14, 2026
132 of 135 checks passed
@junkmd
junkmd deleted the supports_record_info branch November 14, 2026 04:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coding style Topics related to style, formatters, linters, and delinting. enhancement New feature or request typing related to Python static typing system

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants