HomePython Page 3 - Windows Programming in Python: Creating COM Servers
Annotating the Class with Attributes - Python
In an earlier article I discussed accessing COM components from within Python programs. However, I left a question dangling, namely, can COM servers be created in Python, and can they be accessed by applications created in other languages or platforms such as Visual Basic? The answer is an emphatic yes.
Every Python class representing a COM interface must expose itself as a COM object. To achieve this, the PythonCOM framework requires certain attributes to be associated with the Python class that needs to be exposed as a COM object. There are three main attributes, which are:
All of the above attributes are required in exposing a Python class as a COM object - from simplest to the most complex COM objects.
The _public_methods_ attribute takes a list of all those methods that need to be exposed via the COM. The _reg_progid_ attribute is used to assign the ProgID for the new object, that is, the name that the users of this object must use to create the object. It is the human readable name of the object. Finally, the _reg_clsid_ attribute sets the unique CLSID for the object. These IDs must not be copied. Instead new ones should be created using pythoncom.CreateGuid().
Let's take a look at the same example of the COM server:
def double(self, arg): # trivial test function to check it's alive return arg * 2
The _reg_clsid_ contains a 32 bit class id for the object. The _reg_progid_ contains the human readable name using which the object can be called. Here the _public_methods_ contains the list of all the methods exposed via COM. Here there is only one -- double. That completes this section. In the next section, I will be creating a real world example and call it from Visual Basic.