Home/ Reference/ Connection & Init

pythoncom.CoInitialize()

COM initialization; it goes on the first line of the script. Any thread that touches COM has to call it again, or you get "CoInitialize has not been called". Pair it

Signature

pythoncom.CoInitialize()

Notes

COM initialization; it goes on the first line of the script. Any thread that touches COM has to call it again, or you get "CoInitialize has not been called". Pair it with pythoncom.CoUninitialize() at the end.

Python example (runnable)

Requires pywin32. The example assumes app / doc / page / layer are already connected. See Connection & Init
Python
import pythoncom                       # low-level COM module from pywin32

# Start COM for this thread. Required once before any COM call on Windows
pythoncom.CoInitialize()

# Release it when the script ends (keep this habit, always pair the two)
# pythoncom.CoUninitialize()

print("COM is ready")

What this line is for

COM has one hard rule: a thread must declare which apartment it belongs to before it touches COM. pythoncom.CoInitialize() does exactly that — it marks the calling thread as STA (single-threaded apartment).

Why STA matters here: CorelDRAW is an application with a window, a message pump, and UI state. Objects like that have to be pinned to one thread; cross-thread access goes through marshalling, otherwise window messages and internal state get scrambled. It is an STA object, not something any random thread can call into.

What happens if you skip it

The usual text:

Error
pythoncom.com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

That is HRESULT 0x800401F0 (CO_E_NOTINITIALIZED).

It is not necessarily raised on the line that creates the object. Dispatch hands back a dynamic proxy, and only actual calls travel through COM. So the symptom is often "the first few lines ran fine, line 8 blew up" — which makes people blame the method on line 8 instead of the missing initialisation several lines earlier.

Why it sometimes works on the main thread without it

Three reasons, all coincidence, none of them a contract:

So the many tutorial snippets that omit CoInitialize are not wrong, they simply never hit a situation that requires it. Change the thread, move to a service context, run it from Task Scheduler — and it fails immediately.

Return value: S_OK versus S_FALSE

S_OK(0) means this call did the initialisation. S_FALSE(1) means the thread was already initialised in the same apartment and this call only incremented the count. Either way COM is usable, and either way the matching CoUninitialize is owed.

In practice a short-lived script can skip the teardown — COM cleans up when the process exits. A long-running process that creates and destroys threads (a service, a plugin host) must pair the calls, otherwise the count leaks and resources are not released when threads die.

Worker threads always need it

Apartment state is per-thread, not per-process. Every worker in a ThreadPoolExecutor needs its own call:

Python
import threading, pythoncom

_local = threading.local()

def ensure_com():
    if getattr(_local, "ready", False):
        return
    pythoncom.CoInitialize()          # once per thread
    _local.ready = True

The more important rule, though: do not share one app object across threads. CorelDRAW is STA. A proxy obtained on the main thread and used from an MTA thread forces COM to marshal, and pywin32's dynamic proxy has no message pump behind it. The usual outcomes are RPC_E_WRONG_THREAD (0x8001010E) or a call that simply hangs.

CorelDRAW is also a single-instance application, so concurrent access buys you nothing. The structure that works: one thread drives CorelDRAW serially, other threads do file IO and data work, with a queue in between.

CoInitialize versus CoInitializeEx

pythoncom.CoInitialize() is the STA form. For MTA you need pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED).

Initialise a thread one way and then the other and you get 0x80010106 (RPC_E_CHANGED_MODE). That error almost always means "the framework already initialised this process as MTA and then I called CoInitialize() on top". Do not go looking at CorelDRAW when you see it — find out who initialised first.

A complete version

Python
import pythoncom
import win32com.client

def connect(progid="CorelDRAW.Application"):
    pythoncom.CoInitialize()
    try:
        app = win32com.client.Dispatch(progid)
        app.Visible = True
        return app
    except pythoncom.com_error as e:
        hr = e.args[0]
        if hr == -2147221008:
            raise SystemExit("COM not initialised: check CoInitialize on this thread")
        if hr == -2147221005:
            raise SystemExit("Invalid ProgID: check the version suffix or read CurVer")
        if hr == -2147221164:
            raise SystemExit("Class not registered: bitness mismatch is the usual cause")
        raise

app = connect()
print("CorelDRAW", app.Version)

When you can leave it out

Single-threaded, one-shot, interactive desktop scripts usually survive without it. Write it explicitly whenever any of these is true: multiple threads, running as a service or scheduled task, loaded by a host process (VBA calling Python, some RPA tools), or code you will hand to someone else.

The cost of the line is one line. The cost of omitting it is a failure on somebody else's machine months later, with an error message that points at the wrong place.

About this section: Connection & Init

Connection & Init — connecting to CorelDRAW over COM.

Other entries in this section