Using COM Constants

Many COM type libraries also include enumerations, which are named constants and used with the type library. For example, the type library used with Microsoft Excel includes constants named xlAscdending, xlDescending, and so forth, and are used typically as parameters to (or return values from) methods or properties.

These are made available from the Python object win32com.client.constants , for example, win32com.client.constants.xlAscending.

It’s important to note that the constants for a package don’t exist until the MakePy-generated module has been imported; that is, until you create or use an object from the module. You can see this in action if you start Python and attempt to reference a constant from the Microsoft Excel type library:

>>> from win32com.client import constants, Dispatch
>>> constants.xlAscending
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File " win32com\client\__init__.py", line 53, in __getattr__
    raise AttributeError, a
AttributeError: xlAscending
>>>

You can see that attempting to use these constants results in an attribute error. However, if you first create an Excel.Application object, the constants become available:

>>> xl=Dispatch("Excel.Application")
>>> constants.xlAscending
1

Of course, because these constants are read from a type library, they aren’t available when you use late-bound (or dynamic dispatch) objects. In this case, you must use integer literals, rather than named constants in your source code.

Get Python Programming On Win32 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.