The obvious question to arise from this is “How do I control the apartment for my threads or objects?” There is no simple answer.
Fortunately, the rules for threads are quite simple. Before a thread
can use COM, it must call one of the
functions and when it’s done
with COM, it must call
functions are exposed to Python by the
CoInitialize() predates the COM threading models,
so it initializes a new single-threaded apartment for the thread.
CoInitializeEx() takes an additional parameter
that allows you to specify the threading model; thus, you must use
this function to have your thread in the free-threading apartment.
The first single-threaded apartment created (that is, the first
thread that calls either
CoInitializeEx() with the
COINIT_APARTMENTTHREADED flag) is given special
significance as we discuss later, and is known as the main
To hide some of this complexity, Python calls
CoInitializeEx() automatically as soon as the
pythoncom module is imported, and this is
significant for the following reasons:
The threading apartment for the first Python thread that imports the
pythoncom module is controlled by this automatic
process. By default, this thread is initialized in a single-threaded
apartment, but this can be controlled by adding a
co_initflags attribute to the
sys module before importing
pythoncom (see the final sample in this ...