enthought / comtypes

A pure Python, lightweight COM client and server framework, based on the ctypes Python FFI package.
Other
283 stars 96 forks source link

add static typing for when a `CoClass` is assigned as the return value type #542

Closed junkmd closed 1 month ago

junkmd commented 1 month ago

When SomeCoClass is assigned as the return type in the member definition, SomeCoClass._com_interfaces_[0]-type instance is returned at runtime. I have replicated those behavior in static typing.

For example, below is the case with Excel's Range.Application.

...
class Application(CoClass):
    _reg_clsid_ = GUID('{000209FF-0000-0000-C000-000000000046}')
    _idlflags_ = []
    _typelib_path_ = typelib_path
    _reg_typelib_ = ('{00020905-0000-0000-C000-000000000046}', 8, 7)

class _Application(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDispatch):
    _case_insensitive_ = True
    _iid_ = GUID('{00020970-0000-0000-C000-000000000046}')
    _idlflags_ = ['hidden', 'dual', 'nonextensible', 'oleautomation']
    ...

class Range(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDispatch):
    _case_insensitive_ = True
    _iid_ = GUID('{0002095E-0000-0000-C000-000000000046}')
    _idlflags_ = ['dual', 'nonextensible', 'oleautomation']

    if TYPE_CHECKING:  # commembers
        ...
        def _get_Application(self) -> hints.Annotated['_Application', hints.FirstComItfOf['Application']]: ...
        Application = hints.normal_property(_get_Application)
        ...

Range._methods_ = [
    ...
    COMMETHOD(
        [dispid(1000), 'propget'],
        HRESULT,
        'Application',
        (['out', 'retval'], POINTER(POINTER(Application)), 'prop')
    ),
    ...
]

FirstComItfOf assigned to the metadata of Annotated would NOT affect behaviors at runtime, NOR does it control static type checkers. They have no meaning beyond being simple notes.

junkmd commented 1 month ago

CIs are passed.

https://ci.appveyor.com/project/pywinauto/pywinauto/builds/49794425 https://github.com/enthought/comtypes/actions/runs/9044597470