win32com.client.gencache.EnsureDispatch(progid)
Once the constant cache exists you can write cdrTextShape instead of 6. Generating the CorelDRAW type library fails now and then (permissions, version conflicts); wh
Signature
Notes
cdrTextShape instead of 6. Generating the CorelDRAW type library fails now and then (permissions, version conflicts); when it does, fall back to dynamic.Dispatch and use the numeric constants.Python example (runnable)
pywin32. The example assumes app / doc / page / layer are already connected.
See Connection & Initimport win32com.client
# with the type library cache you can write cdrTextShape instead of numbers
try:
app = win32com.client.gencache.EnsureDispatch("CorelDRAW.Application.21")
print("Type library cache built, cdrXxx constants are available")
except Exception as e:
# cache generation often fails (permissions, version clash); fall back to late binding
print("Cache failed, falling back to late binding: ", e)
app = win32com.client.dynamic.Dispatch("CorelDRAW.Application.21")
doc = app.ActiveDocument
print("Pages: ", doc.Pages.Count)
The real difference: whether the type library is read
Dispatch is late binding through IDispatch: method names and arguments are
resolved at call time. EnsureDispatch first locates the component's type library, reads the
interfaces, constants, and parameter types out of it, generates a Python module into a local cache,
and returns an object carrying that static information.
Three concrete gains that late binding cannot give you:
- Constants you can actually use. Enumerations defined in the type library (export formats, units, window states) become attributes of the generated module — no more copying magic numbers out of forum posts.
- Argument errors surface before the call. A wrong number of arguments raises
TypeErrorimmediately, instead of an opaque HRESULT from somewhere inside COM. - Editor completion works. Because a real module is generated, the IDE can list methods and properties.
Cost one: the first call is slow
The first EnsureDispatch reads the type library, generates the module, and writes the
cache — hundreds of milliseconds to several seconds. After that it is cached and fast. Irrelevant on
the command line, very noticeable in a script invoked every minute. That kind of workload is better
served by Dispatch.
Cost two: the cache goes stale, and the errors point elsewhere
The cache lives roughly at %LOCALAPPDATA%\Temp\gen_py\<py version>\, or under
site-packages\win32com\gen_py, depending on installation and permissions. Directory names
combine CLSID, lcid, and version.
The classic failure: CorelDRAW is upgraded, the old cache directory is still there, and the ProgID stem has not changed, so Python keeps loading the stale module. The symptom is not "type library not found", it is:
AttributeError: 'module' object has no attribute 'xxx'— the newer property does not exist in the old cached module.- Argument counts that no longer match, or a member that was cached as a method but is a property in the new version.
ImportError: No module named 'win32com.gen_py.XXXXXXXX-....x0x0x0'— a half-written cache directory.
The fix is direct: stop every Python process, delete the matching directory under
gen_py, and let it regenerate. Put that line in your upgrade checklist; it costs far less
than diagnosing it after the fact.
Cost three: concurrent first-generation races
Several processes calling EnsureDispatch on the same ProgID for the first time all write
into the same directory at once, producing a truncated module or an ImportError. This shows
up in CI, in container startup, and in multiprocessing batch runs.
Avoid it by pre-warming: run `python -c "import win32com.client as w; w.gencache.EnsureDispatch('CorelDRAW.Application')"` during image build or first deployment so the cache is baked in and nothing needs writing at runtime. The pre-warm has to happen with the same interpreter bitness and the same user context as the real run.
One behaviour difference that confuses people
Under gencache, indexed collection access changes shape. With late binding doc.Pages(1)
works; under gencache you more often need doc.Pages.Item(1), and some properties become
methods. This is not a bug — it follows from the type library declaring the member as a parameterised
propget.
When you hit TypeError: 'method' object is not callable, or the mirror-image error, first
establish which binding you are on, then adjust the call.
A complete version
import pythoncom
import win32com.client
from win32com.client import gencache
def connect_typed(progid="CorelDRAW.Application"):
pythoncom.CoInitialize()
try:
app = gencache.EnsureDispatch(progid)
except Exception as e:
# stale or half-written cache is the usual cause
print("EnsureDispatch failed:", e)
print("If it keeps failing, delete the matching dir under %LOCALAPPDATA%\\Temp\\gen_py")
app = win32com.client.Dispatch(progid)
app.Visible = True
print("version:", app.Version)
return app
app = connect_typed()
How to choose
- Use
Dispatch: short scripts, batch jobs, deployment to many machines, no appetite for cache management. It is lighter and easier to debug — errors come from COM itself with no cache factor mixed in. - Use
EnsureDispatch: heavy use of enum constants, long-lived code, wanting IDE completion, or APIs with enough parameters that late binding invites typos. The price is adding cache cleanup to your deployment process. - Do not mix the two for the same ProgID in one codebase. Objects from the two
bindings differ in collection access and property-call semantics; mixing produces
TypeErrors that are painful to reproduce.
About this section: Connection & Init
Connection & Init — connecting to CorelDRAW over COM.
- This section has 8 entries; this is one of them.
- See the full section index: Connection & Init
Other entries in this section
- pythoncom.CoInitialize()COM initialization; it goes on the first line of the script. Any threa
- win32com.client.Dispatch("CorelDRAW.Application.21")Connect by version number; 21 is CorelDRAW 2019. If CDR is already run
- app.Visible = TrueShows the CDR window. Setting it False is faster for batch runs, but k
- win32com.client.Dispatch("CorelDRAW.Application")No version number, so it binds to whatever version is registered as de
- win32com.client.GetActiveObject("CorelDRAW.Application.21")Attaches to an instance that is already open and never starts a new pr
- app.VersionReturns the version as a string. Use it to confirm which version you a
- app.Quit()Closes CorelDRAW entirely. Don't call it at the end of a batch job — i