Via
import win32com.client
wordapp = win32com.client.gencache.EnsureDispatch('Word.Application')
I can get a Word Application
object documented e.g. here. However, ipython
's autocompletion is not aware of that API, is there any way to add that?
Quick solution
Perhaps the simplest way to achieve code completion in IPython (tested with 6.2.1) and Jupyter is to run the following snippet:
Short story long
With some more details being outlined in this guide,
win32com
ships with a script,makepy.py
for generating Python types corresponding to the type library of a given COM object.In the case of Word 2016, we would proceed as follows:
The location of
makepy.py
will of course depend on your Python distribution. The scriptcombrowse.py
, available in the same directory, can be used to find the names of available type libraries.With that in place,
win32com.client
will automatically make use of the generated types, rather than the rawIPyDispatch
, and at this point, auto-completion is available in e.g. IPython or Jupyter, given that the COM object of interest actually publishes its available properties and methods (which is not a requirement).Now, in your case, by invoking
EnsureDispatch
instead ofDispatch
, themakepy
part of the process is performed automatically, so you really should be able to obtain code completion in IPython for the published methods:Note, though, that while this does give code completion for methods, the same will not be true for properties. It is possible to inspect those using the
_prop_map_get_
attribute. For example,wordapp.Selection.Range.Font._prop_map_get_
gives all properties available on fonts.If using IPython is not a strong requirement, note also that the PythonWin shell (located around
\pkgs\pywin32\Lib\site-packages\pythonwin\Pythonwin.exe
) has built-in code completion support for both properties and methods.This, by itself, suggests that the same is achievable in IPython.
Concretely, the logic for auto-completion, which in turn relies on
_prop_map_get_
, can be found inscintilla.view.CScintillaView._AutoComplete
. On the other hand, code completion in IPython 6.2.1 is handled bycore.completer.IPCompleter
. The API for adding custom code completers is provided byIPython.utils.generics.complete_object
, as illustrated in the first solution above. One gotcha is that withcomplete_object
being based onsimplegeneric
, only one completer may be provided for any given type. Luckily, all types generated bymakepy
will inherit fromwin32com.client.DispatchBaseClass
.If this turns out to ever be an issue, one can also circumvent
complete_object
entirely and simply manually patch IPython by adding the following five lines tocore.completer.Completion.attr_matches
:Conversely, IPython bases its code-completion on
__dir__
, so one could also patchgencache
, which is where the code generation ultimately happens, to include something to liketo each generated
DispatchBaseClass
.