Get the base OLE object identifier for Win32com automation objects
Most of Python's built-in types and libraries allow you to return the same object ( a is b
and not just a==b
), even if you ask for it differently. A very simple example:
list = [ "foo", "bar", {"name": [1,2,3]} ]
a = list[-1]["name"]
b = list[2].values()[0]
print (a is b) # True!
However, this does not seem to be the case for many kinds of non-scalar objects returned by automation win32com
. The following code connects to sas-jmp and then gets two handles for the same data table object. At the Python level, these two automation objects have no identifier:
from win32com.client import gencache
mod = gencache.GetModuleForProgID("JMP.Application")
app = mod.Application()
table = app.GetTableHandleFromName("Table1")
same_table = app.GetTableHandleFromName("Table1")
print table
print same_table
print table is same_table
# <win32com.gen_py.DCD36DE0-78F8-11CF-9E68-0020AF24E9FEx0x1x0.IAutoDataTable instance at 0x54418504>
# <win32com.gen_py.DCD36DE0-78F8-11CF-9E68-0020AF24E9FEx0x1x0.IAutoDataTable instance at 0x54432456>
# False
It looks like all win32com
OLE automation objects also have a property _oleobj_
. _oleobj_
is a Pyifispatch object that only has a few methods, none of which are relevant to the question of object identity. However, repr()
of _oleobj_
seems to point to the main OLE automation object:
print table._oleobj_
print same_table._oleobj_
# <PyIDispatch at 0x0000000003459530 with obj at 0x00000000003E2928>
# <PyIDispatch at 0x0000000003459620 with obj at 0x00000000003E2928>
To confirm that the two objects refer to the same underlying OLE object, I resorted to string parsing repr()
and hexadecimal address comparison (" obj at 0x...
").
Is there a better, cleaner way to compare OLE Object ID with win32com
?
source to share
* Removes itself in the face *
It turns out to be a pretty simple way to do it: http://mail.python.org/pipermail/python-win32/2014-October/013288.html
Although the operator is
does not work, since Python objects are different, the object ==
does the job using win32com
-locked objects:
from win32com.client import gencache
mod = gencache.GetModuleForProgID("JMP.Application")
app = mod.Application()
table = app.GetTableHandleFromName("Table1")
same_table = app.GetTableHandleFromName("Table1")
print table is same_table, table._oleobj_ is same_table._oleobj_
print table==same_table, table._oleobj_==same_table._oleobj_
# False, False
# True, True
source to share