O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

What Apartment Do I Live in?

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 CoInitialize() or CoInitializeEx() functions and when it’s done with COM, it must call CoUninitialize(); these functions are exposed to Python by the pythoncom module. 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 CoInitialize() or CoInitializeEx() with the COINIT_APARTMENTTHREADED flag) is given special significance as we discuss later, and is known as the main single-threaded apartment.

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required