dynamic.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. """Support for dynamic COM client support.
  2. Introduction
  3. Dynamic COM client support is the ability to use a COM server without
  4. prior knowledge of the server. This can be used to talk to almost all
  5. COM servers, including much of MS Office.
  6. In general, you should not use this module directly - see below.
  7. Example
  8. >>> import win32com.client
  9. >>> xl = win32com.client.Dispatch("Excel.Application")
  10. # The line above invokes the functionality of this class.
  11. # xl is now an object we can use to talk to Excel.
  12. >>> xl.Visible = 1 # The Excel window becomes visible.
  13. """
  14. import sys
  15. import traceback
  16. import types
  17. import pythoncom
  18. import winerror
  19. from . import build
  20. from pywintypes import IIDType
  21. import win32com.client # Needed as code we eval() references it.
  22. debugging=0 # General debugging
  23. debugging_attr=0 # Debugging dynamic attribute lookups.
  24. LCID = 0x0
  25. # These errors generally mean the property or method exists,
  26. # but can't be used in this context - eg, property instead of a method, etc.
  27. # Used to determine if we have a real error or not.
  28. ERRORS_BAD_CONTEXT = [
  29. winerror.DISP_E_MEMBERNOTFOUND,
  30. winerror.DISP_E_BADPARAMCOUNT,
  31. winerror.DISP_E_PARAMNOTOPTIONAL,
  32. winerror.DISP_E_TYPEMISMATCH,
  33. winerror.E_INVALIDARG,
  34. ]
  35. ALL_INVOKE_TYPES = [
  36. pythoncom.INVOKE_PROPERTYGET,
  37. pythoncom.INVOKE_PROPERTYPUT,
  38. pythoncom.INVOKE_PROPERTYPUTREF,
  39. pythoncom.INVOKE_FUNC
  40. ]
  41. def debug_print(*args):
  42. if debugging:
  43. for arg in args:
  44. print(arg, end=' ')
  45. print()
  46. def debug_attr_print(*args):
  47. if debugging_attr:
  48. for arg in args:
  49. print(arg, end=' ')
  50. print()
  51. def MakeMethod(func, inst, cls):
  52. return types.MethodType(func, inst)
  53. # get the type objects for IDispatch and IUnknown
  54. PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
  55. PyIUnknownType = pythoncom.TypeIIDs[pythoncom.IID_IUnknown]
  56. _GoodDispatchTypes=(str, IIDType)
  57. _defaultDispatchItem=build.DispatchItem
  58. def _GetGoodDispatch(IDispatch, clsctx = pythoncom.CLSCTX_SERVER):
  59. # quick return for most common case
  60. if isinstance(IDispatch, PyIDispatchType):
  61. return IDispatch
  62. if isinstance(IDispatch, _GoodDispatchTypes):
  63. try:
  64. IDispatch = pythoncom.connect(IDispatch)
  65. except pythoncom.ole_error:
  66. IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
  67. else:
  68. # may already be a wrapped class.
  69. IDispatch = getattr(IDispatch, "_oleobj_", IDispatch)
  70. return IDispatch
  71. def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx):
  72. # Get a dispatch object, and a 'user name' (ie, the name as
  73. # displayed to the user in repr() etc.
  74. if userName is None:
  75. if isinstance(IDispatch, str):
  76. userName = IDispatch
  77. ## ??? else userName remains None ???
  78. else:
  79. userName = str(userName)
  80. return (_GetGoodDispatch(IDispatch, clsctx), userName)
  81. def _GetDescInvokeType(entry, invoke_type):
  82. # determine the wFlags argument passed as input to IDispatch::Invoke
  83. # Only ever called by __getattr__ and __setattr__ from dynamic objects!
  84. # * `entry` is a MapEntry with whatever typeinfo we have about the property we are getting/setting.
  85. # * `invoke_type` is either INVOKE_PROPERTYGET | INVOKE_PROPERTYSET and really just
  86. # means "called by __getattr__" or "called by __setattr__"
  87. if not entry or not entry.desc: return invoke_type
  88. if entry.desc.desckind == pythoncom.DESCKIND_VARDESC:
  89. return invoke_type
  90. # So it's a FUNCDESC - just use what it specifies.
  91. return entry.desc.invkind
  92. def Dispatch(IDispatch, userName = None, createClass = None, typeinfo = None, UnicodeToString=None, clsctx = pythoncom.CLSCTX_SERVER):
  93. assert UnicodeToString is None, "this is deprecated and will go away"
  94. IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx)
  95. if createClass is None:
  96. createClass = CDispatch
  97. lazydata = None
  98. try:
  99. if typeinfo is None:
  100. typeinfo = IDispatch.GetTypeInfo()
  101. if typeinfo is not None:
  102. try:
  103. #try for a typecomp
  104. typecomp = typeinfo.GetTypeComp()
  105. lazydata = typeinfo, typecomp
  106. except pythoncom.com_error:
  107. pass
  108. except pythoncom.com_error:
  109. typeinfo = None
  110. olerepr = MakeOleRepr(IDispatch, typeinfo, lazydata)
  111. return createClass(IDispatch, olerepr, userName, lazydata=lazydata)
  112. def MakeOleRepr(IDispatch, typeinfo, typecomp):
  113. olerepr = None
  114. if typeinfo is not None:
  115. try:
  116. attr = typeinfo.GetTypeAttr()
  117. # If the type info is a special DUAL interface, magically turn it into
  118. # a DISPATCH typeinfo.
  119. if attr[5] == pythoncom.TKIND_INTERFACE and attr[11] & pythoncom.TYPEFLAG_FDUAL:
  120. # Get corresponding Disp interface;
  121. # -1 is a special value which does this for us.
  122. href = typeinfo.GetRefTypeOfImplType(-1);
  123. typeinfo = typeinfo.GetRefTypeInfo(href)
  124. attr = typeinfo.GetTypeAttr()
  125. if typecomp is None:
  126. olerepr = build.DispatchItem(typeinfo, attr, None, 0)
  127. else:
  128. olerepr = build.LazyDispatchItem(attr, None)
  129. except pythoncom.ole_error:
  130. pass
  131. if olerepr is None: olerepr = build.DispatchItem()
  132. return olerepr
  133. def DumbDispatch(IDispatch, userName = None, createClass = None,UnicodeToString=None, clsctx=pythoncom.CLSCTX_SERVER):
  134. "Dispatch with no type info"
  135. assert UnicodeToString is None, "this is deprecated and will go away"
  136. IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx)
  137. if createClass is None:
  138. createClass = CDispatch
  139. return createClass(IDispatch, build.DispatchItem(), userName)
  140. class CDispatch:
  141. def __init__(self, IDispatch, olerepr, userName=None, UnicodeToString=None, lazydata=None):
  142. assert UnicodeToString is None, "this is deprecated and will go away"
  143. if userName is None: userName = "<unknown>"
  144. self.__dict__['_oleobj_'] = IDispatch
  145. self.__dict__['_username_'] = userName
  146. self.__dict__['_olerepr_'] = olerepr
  147. self.__dict__['_mapCachedItems_'] = {}
  148. self.__dict__['_builtMethods_'] = {}
  149. self.__dict__['_enum_'] = None
  150. self.__dict__['_unicode_to_string_'] = None
  151. self.__dict__['_lazydata_'] = lazydata
  152. def __call__(self, *args):
  153. "Provide 'default dispatch' COM functionality - allow instance to be called"
  154. if self._olerepr_.defaultDispatchName:
  155. invkind, dispid = self._find_dispatch_type_(self._olerepr_.defaultDispatchName)
  156. else:
  157. invkind, dispid = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, pythoncom.DISPID_VALUE
  158. if invkind is not None:
  159. allArgs = (dispid,LCID,invkind,1) + args
  160. return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
  161. raise TypeError("This dispatch object does not define a default method")
  162. def __bool__(self):
  163. return True # ie "if object:" should always be "true" - without this, __len__ is tried.
  164. # _Possibly_ want to defer to __len__ if available, but Im not sure this is
  165. # desirable???
  166. def __repr__(self):
  167. return "<COMObject %s>" % (self._username_)
  168. def __str__(self):
  169. # __str__ is used when the user does "print object", so we gracefully
  170. # fall back to the __repr__ if the object has no default method.
  171. try:
  172. return str(self.__call__())
  173. except pythoncom.com_error as details:
  174. if details.hresult not in ERRORS_BAD_CONTEXT:
  175. raise
  176. return self.__repr__()
  177. def __dir__(self):
  178. lst = list(self.__dict__.keys()) + dir(self.__class__) + self._dir_ole_()
  179. try: lst += [p.Name for p in self.Properties_]
  180. except AttributeError:
  181. pass
  182. return list(set(lst))
  183. def _dir_ole_(self):
  184. items_dict = {}
  185. for iTI in range(0, self._oleobj_.GetTypeInfoCount()):
  186. typeInfo = self._oleobj_.GetTypeInfo(iTI)
  187. self._UpdateWithITypeInfo_(items_dict, typeInfo)
  188. return list(items_dict.keys())
  189. def _UpdateWithITypeInfo_ (self, items_dict, typeInfo):
  190. typeInfos = [typeInfo]
  191. # suppress IDispatch and IUnknown methods
  192. inspectedIIDs = {pythoncom.IID_IDispatch:None}
  193. while len(typeInfos)>0:
  194. typeInfo = typeInfos.pop()
  195. typeAttr = typeInfo.GetTypeAttr()
  196. if typeAttr.iid not in inspectedIIDs:
  197. inspectedIIDs[typeAttr.iid] = None
  198. for iFun in range(0,typeAttr.cFuncs):
  199. funDesc = typeInfo.GetFuncDesc(iFun)
  200. funName = typeInfo.GetNames(funDesc.memid)[0]
  201. if funName not in items_dict:
  202. items_dict[funName] = None
  203. # Inspect the type info of all implemented types
  204. # E.g. IShellDispatch5 implements IShellDispatch4 which implements IShellDispatch3 ...
  205. for iImplType in range(0,typeAttr.cImplTypes):
  206. iRefType = typeInfo.GetRefTypeOfImplType(iImplType)
  207. refTypeInfo = typeInfo.GetRefTypeInfo(iRefType)
  208. typeInfos.append(refTypeInfo)
  209. # Delegate comparison to the oleobjs, as they know how to do identity.
  210. def __eq__(self, other):
  211. other = getattr(other, "_oleobj_", other)
  212. return self._oleobj_ == other
  213. def __ne__(self, other):
  214. other = getattr(other, "_oleobj_", other)
  215. return self._oleobj_ != other
  216. def __int__(self):
  217. return int(self.__call__())
  218. def __len__(self):
  219. invkind, dispid = self._find_dispatch_type_("Count")
  220. if invkind:
  221. return self._oleobj_.Invoke(dispid, LCID, invkind, 1)
  222. raise TypeError("This dispatch object does not define a Count method")
  223. def _NewEnum(self):
  224. try:
  225. invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
  226. enum = self._oleobj_.InvokeTypes(pythoncom.DISPID_NEWENUM,LCID,invkind,(13, 10),())
  227. except pythoncom.com_error:
  228. return None # no enumerator for this object.
  229. from . import util
  230. return util.WrapEnum(enum, None)
  231. def __getitem__(self, index): # syver modified
  232. # Improved __getitem__ courtesy Syver Enstad
  233. # Must check _NewEnum before Item, to ensure b/w compat.
  234. if isinstance(index, int):
  235. if self.__dict__['_enum_'] is None:
  236. self.__dict__['_enum_'] = self._NewEnum()
  237. if self.__dict__['_enum_'] is not None:
  238. return self._get_good_object_(self._enum_.__getitem__(index))
  239. # See if we have an "Item" method/property we can use (goes hand in hand with Count() above!)
  240. invkind, dispid = self._find_dispatch_type_("Item")
  241. if invkind is not None:
  242. return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
  243. raise TypeError("This object does not support enumeration")
  244. def __setitem__(self, index, *args):
  245. # XXX - todo - We should support calling Item() here too!
  246. # print "__setitem__ with", index, args
  247. if self._olerepr_.defaultDispatchName:
  248. invkind, dispid = self._find_dispatch_type_(self._olerepr_.defaultDispatchName)
  249. else:
  250. invkind, dispid = pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF, pythoncom.DISPID_VALUE
  251. if invkind is not None:
  252. allArgs = (dispid,LCID,invkind,0,index) + args
  253. return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
  254. raise TypeError("This dispatch object does not define a default method")
  255. def _find_dispatch_type_(self, methodName):
  256. if methodName in self._olerepr_.mapFuncs:
  257. item = self._olerepr_.mapFuncs[methodName]
  258. return item.desc[4], item.dispid
  259. if methodName in self._olerepr_.propMapGet:
  260. item = self._olerepr_.propMapGet[methodName]
  261. return item.desc[4], item.dispid
  262. try:
  263. dispid = self._oleobj_.GetIDsOfNames(0,methodName)
  264. except: ### what error?
  265. return None, None
  266. return pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid
  267. def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
  268. result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
  269. return self._get_good_object_(result, user, resultCLSID)
  270. def _wrap_dispatch_(self, ob, userName = None, returnCLSID = None, UnicodeToString=None):
  271. # Given a dispatch object, wrap it in a class
  272. assert UnicodeToString is None, "this is deprecated and will go away"
  273. return Dispatch(ob, userName)
  274. def _get_good_single_object_(self,ob,userName = None, ReturnCLSID=None):
  275. if isinstance(ob, PyIDispatchType):
  276. # make a new instance of (probably this) class.
  277. return self._wrap_dispatch_(ob, userName, ReturnCLSID)
  278. if isinstance(ob, PyIUnknownType):
  279. try:
  280. ob = ob.QueryInterface(pythoncom.IID_IDispatch)
  281. except pythoncom.com_error:
  282. # It is an IUnknown, but not an IDispatch, so just let it through.
  283. return ob
  284. return self._wrap_dispatch_(ob, userName, ReturnCLSID)
  285. return ob
  286. def _get_good_object_(self,ob,userName = None, ReturnCLSID=None):
  287. """Given an object (usually the retval from a method), make it a good object to return.
  288. Basically checks if it is a COM object, and wraps it up.
  289. Also handles the fact that a retval may be a tuple of retvals"""
  290. if ob is None: # Quick exit!
  291. return None
  292. elif isinstance(ob, tuple):
  293. return tuple(map(lambda o, s=self, oun=userName, rc=ReturnCLSID: s._get_good_single_object_(o, oun, rc), ob))
  294. else:
  295. return self._get_good_single_object_(ob)
  296. def _make_method_(self, name):
  297. "Make a method object - Assumes in olerepr funcmap"
  298. methodName = build.MakePublicAttributeName(name) # translate keywords etc.
  299. methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0)
  300. methodCode = "\n".join(methodCodeList)
  301. try:
  302. # print "Method code for %s is:\n" % self._username_, methodCode
  303. # self._print_details_()
  304. codeObject = compile(methodCode, "<COMObject %s>" % self._username_,"exec")
  305. # Exec the code object
  306. tempNameSpace = {}
  307. # "Dispatch" in the exec'd code is win32com.client.Dispatch, not ours.
  308. globNameSpace = globals().copy()
  309. globNameSpace["Dispatch"] = win32com.client.Dispatch
  310. exec(codeObject, globNameSpace, tempNameSpace) # self.__dict__, self.__dict__
  311. name = methodName
  312. # Save the function in map.
  313. fn = self._builtMethods_[name] = tempNameSpace[name]
  314. newMeth = MakeMethod(fn, self, self.__class__)
  315. return newMeth
  316. except:
  317. debug_print("Error building OLE definition for code ", methodCode)
  318. traceback.print_exc()
  319. return None
  320. def _Release_(self):
  321. """Cleanup object - like a close - to force cleanup when you dont
  322. want to rely on Python's reference counting."""
  323. for childCont in self._mapCachedItems_.values():
  324. childCont._Release_()
  325. self._mapCachedItems_ = {}
  326. if self._oleobj_:
  327. self._oleobj_.Release()
  328. self.__dict__['_oleobj_'] = None
  329. if self._olerepr_:
  330. self.__dict__['_olerepr_'] = None
  331. self._enum_ = None
  332. def _proc_(self, name, *args):
  333. """Call the named method as a procedure, rather than function.
  334. Mainly used by Word.Basic, which whinges about such things."""
  335. try:
  336. item = self._olerepr_.mapFuncs[name]
  337. dispId = item.dispid
  338. return self._get_good_object_(self._oleobj_.Invoke(*(dispId, LCID, item.desc[4], 0) + (args) ))
  339. except KeyError:
  340. raise AttributeError(name)
  341. def _print_details_(self):
  342. "Debug routine - dumps what it knows about an object."
  343. print("AxDispatch container",self._username_)
  344. try:
  345. print("Methods:")
  346. for method in self._olerepr_.mapFuncs.keys():
  347. print("\t", method)
  348. print("Props:")
  349. for prop, entry in self._olerepr_.propMap.items():
  350. print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
  351. print("Get Props:")
  352. for prop, entry in self._olerepr_.propMapGet.items():
  353. print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
  354. print("Put Props:")
  355. for prop, entry in self._olerepr_.propMapPut.items():
  356. print("\t%s = 0x%x - %s" % (prop, entry.dispid, repr(entry)))
  357. except:
  358. traceback.print_exc()
  359. def __LazyMap__(self, attr):
  360. try:
  361. if self._LazyAddAttr_(attr):
  362. debug_attr_print("%s.__LazyMap__(%s) added something" % (self._username_,attr))
  363. return 1
  364. except AttributeError:
  365. return 0
  366. # Using the typecomp, lazily create a new attribute definition.
  367. def _LazyAddAttr_(self,attr):
  368. if self._lazydata_ is None: return 0
  369. res = 0
  370. typeinfo, typecomp = self._lazydata_
  371. olerepr = self._olerepr_
  372. # We need to explicitly check each invoke type individually - simply
  373. # specifying '0' will bind to "any member", which may not be the one
  374. # we are actually after (ie, we may be after prop_get, but returned
  375. # the info for the prop_put.)
  376. for i in ALL_INVOKE_TYPES:
  377. try:
  378. x,t = typecomp.Bind(attr,i)
  379. # Support 'Get' and 'Set' properties - see
  380. # bug 1587023
  381. if x==0 and attr[:3] in ('Set', 'Get'):
  382. x,t = typecomp.Bind(attr[3:], i)
  383. if x==pythoncom.DESCKIND_FUNCDESC: #it's a FUNCDESC
  384. r = olerepr._AddFunc_(typeinfo,t,0)
  385. elif x==pythoncom.DESCKIND_VARDESC: #it's a VARDESC
  386. r = olerepr._AddVar_(typeinfo,t,0)
  387. else: #not found or TYPEDESC/IMPLICITAPP
  388. r=None
  389. if not r is None:
  390. key, map = r[0],r[1]
  391. item = map[key]
  392. if map==olerepr.propMapPut:
  393. olerepr._propMapPutCheck_(key,item)
  394. elif map==olerepr.propMapGet:
  395. olerepr._propMapGetCheck_(key,item)
  396. res = 1
  397. except:
  398. pass
  399. return res
  400. def _FlagAsMethod(self, *methodNames):
  401. """Flag these attribute names as being methods.
  402. Some objects do not correctly differentiate methods and
  403. properties, leading to problems when calling these methods.
  404. Specifically, trying to say: ob.SomeFunc()
  405. may yield an exception "None object is not callable"
  406. In this case, an attempt to fetch the *property* has worked
  407. and returned None, rather than indicating it is really a method.
  408. Calling: ob._FlagAsMethod("SomeFunc")
  409. should then allow this to work.
  410. """
  411. for name in methodNames:
  412. details = build.MapEntry(self.__AttrToID__(name), (name,))
  413. self._olerepr_.mapFuncs[name] = details
  414. def __AttrToID__(self,attr):
  415. debug_attr_print("Calling GetIDsOfNames for property %s in Dispatch container %s" % (attr, self._username_))
  416. return self._oleobj_.GetIDsOfNames(0,attr)
  417. def __getattr__(self, attr):
  418. if attr=='__iter__':
  419. # We can't handle this as a normal method, as if the attribute
  420. # exists, then it must return an iterable object.
  421. try:
  422. invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
  423. enum = self._oleobj_.InvokeTypes(pythoncom.DISPID_NEWENUM,LCID,invkind,(13, 10),())
  424. except pythoncom.com_error:
  425. raise AttributeError("This object can not function as an iterator")
  426. # We must return a callable object.
  427. class Factory:
  428. def __init__(self, ob):
  429. self.ob = ob
  430. def __call__(self):
  431. import win32com.client.util
  432. return win32com.client.util.Iterator(self.ob)
  433. return Factory(enum)
  434. if attr.startswith('_') and attr.endswith('_'): # Fast-track.
  435. raise AttributeError(attr)
  436. # If a known method, create new instance and return.
  437. try:
  438. return MakeMethod(self._builtMethods_[attr], self, self.__class__)
  439. except KeyError:
  440. pass
  441. # XXX - Note that we current are case sensitive in the method.
  442. #debug_attr_print("GetAttr called for %s on DispatchContainer %s" % (attr,self._username_))
  443. # First check if it is in the method map. Note that an actual method
  444. # must not yet exist, (otherwise we would not be here). This
  445. # means we create the actual method object - which also means
  446. # this code will never be asked for that method name again.
  447. if attr in self._olerepr_.mapFuncs:
  448. return self._make_method_(attr)
  449. # Delegate to property maps/cached items
  450. retEntry = None
  451. if self._olerepr_ and self._oleobj_:
  452. # first check general property map, then specific "put" map.
  453. retEntry = self._olerepr_.propMap.get(attr)
  454. if retEntry is None:
  455. retEntry = self._olerepr_.propMapGet.get(attr)
  456. # Not found so far - See what COM says.
  457. if retEntry is None:
  458. try:
  459. if self.__LazyMap__(attr):
  460. if attr in self._olerepr_.mapFuncs: return self._make_method_(attr)
  461. retEntry = self._olerepr_.propMap.get(attr)
  462. if retEntry is None:
  463. retEntry = self._olerepr_.propMapGet.get(attr)
  464. if retEntry is None:
  465. retEntry = build.MapEntry(self.__AttrToID__(attr), (attr,))
  466. except pythoncom.ole_error:
  467. pass # No prop by that name - retEntry remains None.
  468. if retEntry is not None: # see if in my cache
  469. try:
  470. ret = self._mapCachedItems_[retEntry.dispid]
  471. debug_attr_print ("Cached items has attribute!", ret)
  472. return ret
  473. except (KeyError, AttributeError):
  474. debug_attr_print("Attribute %s not in cache" % attr)
  475. # If we are still here, and have a retEntry, get the OLE item
  476. if retEntry is not None:
  477. invoke_type = _GetDescInvokeType(retEntry, pythoncom.INVOKE_PROPERTYGET)
  478. debug_attr_print("Getting property Id 0x%x from OLE object" % retEntry.dispid)
  479. try:
  480. ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
  481. except pythoncom.com_error as details:
  482. if details.hresult in ERRORS_BAD_CONTEXT:
  483. # May be a method.
  484. self._olerepr_.mapFuncs[attr] = retEntry
  485. return self._make_method_(attr)
  486. raise
  487. debug_attr_print("OLE returned ", ret)
  488. return self._get_good_object_(ret)
  489. # no where else to look.
  490. raise AttributeError("%s.%s" % (self._username_, attr))
  491. def __setattr__(self, attr, value):
  492. if attr in self.__dict__: # Fast-track - if already in our dict, just make the assignment.
  493. # XXX - should maybe check method map - if someone assigns to a method,
  494. # it could mean something special (not sure what, tho!)
  495. self.__dict__[attr] = value
  496. return
  497. # Allow property assignment.
  498. debug_attr_print("SetAttr called for %s.%s=%s on DispatchContainer" % (self._username_, attr, repr(value)))
  499. if self._olerepr_:
  500. # Check the "general" property map.
  501. if attr in self._olerepr_.propMap:
  502. entry = self._olerepr_.propMap[attr]
  503. invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
  504. self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
  505. return
  506. # Check the specific "put" map.
  507. if attr in self._olerepr_.propMapPut:
  508. entry = self._olerepr_.propMapPut[attr]
  509. invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
  510. self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
  511. return
  512. # Try the OLE Object
  513. if self._oleobj_:
  514. if self.__LazyMap__(attr):
  515. # Check the "general" property map.
  516. if attr in self._olerepr_.propMap:
  517. entry = self._olerepr_.propMap[attr]
  518. invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
  519. self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
  520. return
  521. # Check the specific "put" map.
  522. if attr in self._olerepr_.propMapPut:
  523. entry = self._olerepr_.propMapPut[attr]
  524. invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
  525. self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
  526. return
  527. try:
  528. entry = build.MapEntry(self.__AttrToID__(attr),(attr,))
  529. except pythoncom.com_error:
  530. # No attribute of that name
  531. entry = None
  532. if entry is not None:
  533. try:
  534. invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
  535. self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
  536. self._olerepr_.propMap[attr] = entry
  537. debug_attr_print("__setattr__ property %s (id=0x%x) in Dispatch container %s" % (attr, entry.dispid, self._username_))
  538. return
  539. except pythoncom.com_error:
  540. pass
  541. raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))