enthought / enthought/comtypes
Manual/deterministic releasing of interface pointers
- Dominant language
- Python
- Stars
- 345
- Forks
- 105
- PR merge metrics
- No merged PRs in 30d
Description
I wonder, is it possible to release a COM interface pointer manually by calling `Release()`, instead of waiting for its `__del__` to be called?
The problem of this method is that `Release()` is still called when `__del__` is called.
https://github.com/enthought/comtypes/blob/5c564eca9ec173fceafbdddd570fa5c7e1c6c564/comtypes/_post_coinit/unknwn.py#L272-L284
`__del__()` in Python cannot be used to achieve deterministic destruction, like destructors in C++ do. In the [docs](https://docs.python.org/3/reference/datamodel.html#object.__del__):
> __del__() can be invoked when arbitrary code is being executed, including from any arbitrary thread.
This would cause some problems if I want a certain COM object to be released at or before a certain time.
Although CPython uses reference counting, so *usually* the object will be released when the last reference is removed, it isn't necessarily the case in other Python implementations.
A common solution is to use the context manager. Implement `__enter__` and `__exit__`, so that it can be used in a `with` block, and be automatically released when leaving the `with` block. Many resource objects, such as files, already support the context manager protocol.
Contributor guide
Assessment
This issue has not been assessed yet.