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

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.

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