__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. # This module exists to create the "best" dispatch object for a given
  2. # object. If "makepy" support for a given object is detected, it is
  3. # used, otherwise a dynamic dispatch object.
  4. # Note that if the unknown dispatch object then returns a known
  5. # dispatch object, the known class will be used. This contrasts
  6. # with dynamic.Dispatch behaviour, where dynamic objects are always used.
  7. import pythoncom
  8. from . import dynamic
  9. from . import gencache
  10. import sys
  11. import pywintypes
  12. _PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
  13. def __WrapDispatch(dispatch, userName = None, resultCLSID = None, typeinfo = None, \
  14. UnicodeToString=None, clsctx = pythoncom.CLSCTX_SERVER,
  15. WrapperClass = None):
  16. """
  17. Helper function to return a makepy generated class for a CLSID if it exists,
  18. otherwise cope by using CDispatch.
  19. """
  20. assert UnicodeToString is None, "this is deprecated and will go away"
  21. if resultCLSID is None:
  22. try:
  23. typeinfo = dispatch.GetTypeInfo()
  24. if typeinfo is not None: # Some objects return NULL, some raise exceptions...
  25. resultCLSID = str(typeinfo.GetTypeAttr()[0])
  26. except (pythoncom.com_error, AttributeError):
  27. pass
  28. if resultCLSID is not None:
  29. from . import gencache
  30. # Attempt to load generated module support
  31. # This may load the module, and make it available
  32. klass = gencache.GetClassForCLSID(resultCLSID)
  33. if klass is not None:
  34. return klass(dispatch)
  35. # Return a "dynamic" object - best we can do!
  36. if WrapperClass is None: WrapperClass = CDispatch
  37. return dynamic.Dispatch(dispatch, userName, WrapperClass, typeinfo, clsctx=clsctx)
  38. def GetObject(Pathname = None, Class = None, clsctx = None):
  39. """
  40. Mimic VB's GetObject() function.
  41. ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will
  42. connect to an already running instance of the COM object.
  43. ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax)
  44. will return a ready to use Python wrapping of the required COM object.
  45. Note: You must specifiy one or the other of these arguments. I know
  46. this isn't pretty, but it is what VB does. Blech. If you don't
  47. I'll throw ValueError at you. :)
  48. This will most likely throw pythoncom.com_error if anything fails.
  49. """
  50. if clsctx is None:
  51. clsctx = pythoncom.CLSCTX_ALL
  52. if (Pathname is None and Class is None) or \
  53. (Pathname is not None and Class is not None):
  54. raise ValueError("You must specify a value for Pathname or Class, but not both.")
  55. if Class is not None:
  56. return GetActiveObject(Class, clsctx)
  57. else:
  58. return Moniker(Pathname, clsctx)
  59. def GetActiveObject(Class, clsctx = pythoncom.CLSCTX_ALL):
  60. """
  61. Python friendly version of GetObject's ProgID/CLSID functionality.
  62. """
  63. resultCLSID = pywintypes.IID(Class)
  64. dispatch = pythoncom.GetActiveObject(resultCLSID)
  65. dispatch = dispatch.QueryInterface(pythoncom.IID_IDispatch)
  66. return __WrapDispatch(dispatch, Class, resultCLSID = resultCLSID, clsctx = clsctx)
  67. def Moniker(Pathname, clsctx = pythoncom.CLSCTX_ALL):
  68. """
  69. Python friendly version of GetObject's moniker functionality.
  70. """
  71. moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
  72. dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
  73. return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
  74. def Dispatch(dispatch, userName = None, resultCLSID = None, typeinfo = None, UnicodeToString=None, clsctx = pythoncom.CLSCTX_SERVER):
  75. """Creates a Dispatch based COM object.
  76. """
  77. assert UnicodeToString is None, "this is deprecated and will go away"
  78. dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  79. return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
  80. def DispatchEx(clsid, machine=None, userName = None, resultCLSID = None, typeinfo = None, UnicodeToString=None, clsctx = None):
  81. """Creates a Dispatch based COM object on a specific machine.
  82. """
  83. assert UnicodeToString is None, "this is deprecated and will go away"
  84. # If InProc is registered, DCOM will use it regardless of the machine name
  85. # (and regardless of the DCOM config for the object.) So unless the user
  86. # specifies otherwise, we exclude inproc apps when a remote machine is used.
  87. if clsctx is None:
  88. clsctx = pythoncom.CLSCTX_SERVER
  89. if machine is not None: clsctx = clsctx & ~pythoncom.CLSCTX_INPROC
  90. if machine is None:
  91. serverInfo = None
  92. else:
  93. serverInfo = (machine,)
  94. if userName is None: userName = clsid
  95. dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
  96. return Dispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
  97. class CDispatch(dynamic.CDispatch):
  98. """
  99. The dynamic class used as a last resort.
  100. The purpose of this overriding of dynamic.CDispatch is to perpetuate the policy
  101. of using the makepy generated wrapper Python class instead of dynamic.CDispatch
  102. if/when possible.
  103. """
  104. def _wrap_dispatch_(self, ob, userName = None, returnCLSID = None, UnicodeToString=None):
  105. assert UnicodeToString is None, "this is deprecated and will go away"
  106. return Dispatch(ob, userName, returnCLSID,None)
  107. def __dir__(self):
  108. return dynamic.CDispatch.__dir__(self)
  109. def CastTo(ob, target, typelib = None):
  110. """'Cast' a COM object to another interface"""
  111. # todo - should support target being an IID
  112. mod = None
  113. if typelib is not None: # caller specified target typelib (TypelibSpec). See e.g. selecttlb.EnumTlbs().
  114. mod = gencache.MakeModuleForTypelib(typelib.clsid, typelib.lcid, int(typelib.major, 16), int(typelib.minor, 16))
  115. if not hasattr(mod, target):
  116. raise ValueError("The interface name '%s' does not appear in the " \
  117. "specified library %r" % (target, typelib.ver_desc))
  118. elif hasattr(target, "index"): # string like
  119. # for now, we assume makepy for this to work.
  120. if "CLSID" not in ob.__class__.__dict__:
  121. # Eeek - no makepy support - try and build it.
  122. ob = gencache.EnsureDispatch(ob)
  123. if "CLSID" not in ob.__class__.__dict__:
  124. raise ValueError("Must be a makepy-able object for this to work")
  125. clsid = ob.CLSID
  126. # Lots of hoops to support "demand-build" - ie, generating
  127. # code for an interface first time it is used. We assume the
  128. # interface name exists in the same library as the object.
  129. # This is generally the case - only referenced typelibs may be
  130. # a problem, and we can handle that later. Maybe <wink>
  131. # So get the generated module for the library itself, then
  132. # find the interface CLSID there.
  133. mod = gencache.GetModuleForCLSID(clsid)
  134. # Get the 'root' module.
  135. mod = gencache.GetModuleForTypelib(mod.CLSID, mod.LCID,
  136. mod.MajorVersion, mod.MinorVersion)
  137. # Find the CLSID of the target
  138. target_clsid = mod.NamesToIIDMap.get(target)
  139. if target_clsid is None:
  140. raise ValueError("The interface name '%s' does not appear in the " \
  141. "same library as object '%r'" % (target, ob))
  142. mod = gencache.GetModuleForCLSID(target_clsid)
  143. if mod is not None:
  144. target_class = getattr(mod, target)
  145. # resolve coclass to interface
  146. target_class = getattr(target_class, "default_interface", target_class)
  147. return target_class(ob) # auto QI magic happens
  148. raise ValueError
  149. class Constants:
  150. """A container for generated COM constants.
  151. """
  152. def __init__(self):
  153. self.__dicts__ = [] # A list of dictionaries
  154. def __getattr__(self, a):
  155. for d in self.__dicts__:
  156. if a in d:
  157. return d[a]
  158. raise AttributeError(a)
  159. # And create an instance.
  160. constants = Constants()
  161. # A helpers for DispatchWithEvents - this becomes __setattr__ for the
  162. # temporary class.
  163. def _event_setattr_(self, attr, val):
  164. try:
  165. # Does the COM object have an attribute of this name?
  166. self.__class__.__bases__[0].__setattr__(self, attr, val)
  167. except AttributeError:
  168. # Otherwise just stash it away in the instance.
  169. self.__dict__[attr] = val
  170. # An instance of this "proxy" is created to break the COM circular references
  171. # that exist (ie, when we connect to the COM events, COM keeps a reference
  172. # to the object. Thus, the Event connection must be manually broken before
  173. # our object can die. This solves the problem by manually breaking the connection
  174. # to the real object as the proxy dies.
  175. class EventsProxy:
  176. def __init__(self, ob):
  177. self.__dict__['_obj_'] = ob
  178. def __del__(self):
  179. try:
  180. # If there is a COM error on disconnection we should
  181. # just ignore it - object probably already shut down...
  182. self._obj_.close()
  183. except pythoncom.com_error:
  184. pass
  185. def __getattr__(self, attr):
  186. return getattr(self._obj_, attr)
  187. def __setattr__(self, attr, val):
  188. setattr(self._obj_, attr, val)
  189. def DispatchWithEvents(clsid, user_event_class):
  190. """Create a COM object that can fire events to a user defined class.
  191. clsid -- The ProgID or CLSID of the object to create.
  192. user_event_class -- A Python class object that responds to the events.
  193. This requires makepy support for the COM object being created. If
  194. this support does not exist it will be automatically generated by
  195. this function. If the object does not support makepy, a TypeError
  196. exception will be raised.
  197. The result is a class instance that both represents the COM object
  198. and handles events from the COM object.
  199. It is important to note that the returned instance is not a direct
  200. instance of the user_event_class, but an instance of a temporary
  201. class object that derives from three classes:
  202. * The makepy generated class for the COM object
  203. * The makepy generated class for the COM events
  204. * The user_event_class as passed to this function.
  205. If this is not suitable, see the getevents function for an alternative
  206. technique of handling events.
  207. Object Lifetimes: Whenever the object returned from this function is
  208. cleaned-up by Python, the events will be disconnected from
  209. the COM object. This is almost always what should happen,
  210. but see the documentation for getevents() for more details.
  211. Example:
  212. >>> class IEEvents:
  213. ... def OnVisible(self, visible):
  214. ... print "Visible changed:", visible
  215. ...
  216. >>> ie = DispatchWithEvents("InternetExplorer.Application", IEEvents)
  217. >>> ie.Visible = 1
  218. Visible changed: 1
  219. >>>
  220. """
  221. # Create/Get the object.
  222. disp = Dispatch(clsid)
  223. if not disp.__class__.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
  224. try:
  225. ti = disp._oleobj_.GetTypeInfo()
  226. disp_clsid = ti.GetTypeAttr()[0]
  227. tlb, index = ti.GetContainingTypeLib()
  228. tla = tlb.GetLibAttr()
  229. gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
  230. # Get the class from the module.
  231. disp_class = gencache.GetClassForProgID(str(disp_clsid))
  232. except pythoncom.com_error:
  233. raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
  234. else:
  235. disp_class = disp.__class__
  236. # If the clsid was an object, get the clsid
  237. clsid = disp_class.CLSID
  238. # Create a new class that derives from 3 classes - the dispatch class, the event sink class and the user class.
  239. # XXX - we are still "classic style" classes in py2x, so we need can't yet
  240. # use 'type()' everywhere - revisit soon, as py2x will move to new-style too...
  241. try:
  242. from types import ClassType as new_type
  243. except ImportError:
  244. new_type = type # py3k
  245. events_class = getevents(clsid)
  246. if events_class is None:
  247. raise ValueError("This COM object does not support events.")
  248. result_class = new_type("COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__" : _event_setattr_})
  249. instance = result_class(disp._oleobj_) # This only calls the first base class __init__.
  250. events_class.__init__(instance, instance)
  251. if hasattr(user_event_class, "__init__"):
  252. user_event_class.__init__(instance)
  253. return EventsProxy(instance)
  254. def WithEvents(disp, user_event_class):
  255. """Similar to DispatchWithEvents - except that the returned
  256. object is *not* also usable as the original Dispatch object - that is
  257. the returned object is not dispatchable.
  258. The difference is best summarised by example.
  259. >>> class IEEvents:
  260. ... def OnVisible(self, visible):
  261. ... print "Visible changed:", visible
  262. ...
  263. >>> ie = Dispatch("InternetExplorer.Application")
  264. >>> ie_events = WithEvents(ie, IEEvents)
  265. >>> ie.Visible = 1
  266. Visible changed: 1
  267. Compare with the code sample for DispatchWithEvents, where you get a
  268. single object that is both the interface and the event handler. Note that
  269. the event handler instance will *not* be able to use 'self.' to refer to
  270. IE's methods and properties.
  271. This is mainly useful where using DispatchWithEvents causes
  272. circular reference problems that the simple proxy doesn't deal with
  273. """
  274. disp = Dispatch(disp)
  275. if not disp.__class__.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
  276. try:
  277. ti = disp._oleobj_.GetTypeInfo()
  278. disp_clsid = ti.GetTypeAttr()[0]
  279. tlb, index = ti.GetContainingTypeLib()
  280. tla = tlb.GetLibAttr()
  281. gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
  282. # Get the class from the module.
  283. disp_class = gencache.GetClassForProgID(str(disp_clsid))
  284. except pythoncom.com_error:
  285. raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
  286. else:
  287. disp_class = disp.__class__
  288. # Get the clsid
  289. clsid = disp_class.CLSID
  290. # Create a new class that derives from 2 classes - the event sink
  291. # class and the user class.
  292. try:
  293. from types import ClassType as new_type
  294. except ImportError:
  295. new_type = type # py3k
  296. events_class = getevents(clsid)
  297. if events_class is None:
  298. raise ValueError("This COM object does not support events.")
  299. result_class = new_type("COMEventClass", (events_class, user_event_class), {})
  300. instance = result_class(disp) # This only calls the first base class __init__.
  301. if hasattr(user_event_class, "__init__"):
  302. user_event_class.__init__(instance)
  303. return instance
  304. def getevents(clsid):
  305. """Determine the default outgoing interface for a class, given
  306. either a clsid or progid. It returns a class - you can
  307. conveniently derive your own handler from this class and implement
  308. the appropriate methods.
  309. This method relies on the classes produced by makepy. You must use
  310. either makepy or the gencache module to ensure that the
  311. appropriate support classes have been generated for the com server
  312. that you will be handling events from.
  313. Beware of COM circular references. When the Events class is connected
  314. to the COM object, the COM object itself keeps a reference to the Python
  315. events class. Thus, neither the Events instance or the COM object will
  316. ever die by themselves. The 'close' method on the events instance
  317. must be called to break this chain and allow standard Python collection
  318. rules to manage object lifetimes. Note that DispatchWithEvents() does
  319. work around this problem by the use of a proxy object, but if you use
  320. the getevents() function yourself, you must make your own arrangements
  321. to manage this circular reference issue.
  322. Beware of creating Python circular references: this will happen if your
  323. handler has a reference to an object that has a reference back to
  324. the event source. Call the 'close' method to break the chain.
  325. Example:
  326. >>>win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}',0,1,1)
  327. <module 'win32com.gen_py.....
  328. >>>
  329. >>> class InternetExplorerEvents(win32com.client.getevents("InternetExplorer.Application.1")):
  330. ... def OnVisible(self, Visible):
  331. ... print "Visibility changed: ", Visible
  332. ...
  333. >>>
  334. >>> ie=win32com.client.Dispatch("InternetExplorer.Application.1")
  335. >>> events=InternetExplorerEvents(ie)
  336. >>> ie.Visible=1
  337. Visibility changed: 1
  338. >>>
  339. """
  340. # find clsid given progid or clsid
  341. clsid=str(pywintypes.IID(clsid))
  342. # return default outgoing interface for that class
  343. klass = gencache.GetClassForCLSID(clsid)
  344. try:
  345. return klass.default_source
  346. except AttributeError:
  347. # See if we have a coclass for the interfaces.
  348. try:
  349. return gencache.GetClassForCLSID(klass.coclass_clsid).default_source
  350. except AttributeError:
  351. return None
  352. # A Record object, as used by the COM struct support
  353. def Record(name, object):
  354. """Creates a new record object, given the name of the record,
  355. and an object from the same type library.
  356. Example usage would be:
  357. app = win32com.client.Dispatch("Some.Application")
  358. point = win32com.client.Record("SomeAppPoint", app)
  359. point.x = 0
  360. point.y = 0
  361. app.MoveTo(point)
  362. """
  363. # XXX - to do - probably should allow "object" to already be a module object.
  364. from . import gencache
  365. object = gencache.EnsureDispatch(object)
  366. module = sys.modules[object.__class__.__module__]
  367. # to allow us to work correctly with "demand generated" code,
  368. # we must use the typelib CLSID to obtain the module
  369. # (otherwise we get the sub-module for the object, which
  370. # does not hold the records)
  371. # thus, package may be module, or may be module's parent if demand generated.
  372. package = gencache.GetModuleForTypelib(module.CLSID, module.LCID, module.MajorVersion, module.MinorVersion)
  373. try:
  374. struct_guid = package.RecordMap[name]
  375. except KeyError:
  376. raise ValueError("The structure '%s' is not defined in module '%s'" % (name, package))
  377. return pythoncom.GetRecordFromGuids(module.CLSID, module.MajorVersion, module.MinorVersion, module.LCID, struct_guid)
  378. ############################################
  379. # The base of all makepy generated classes
  380. ############################################
  381. class DispatchBaseClass:
  382. def __init__(self, oobj=None):
  383. if oobj is None:
  384. oobj = pythoncom.new(self.CLSID)
  385. elif isinstance(oobj, DispatchBaseClass):
  386. try:
  387. oobj = oobj._oleobj_.QueryInterface(self.CLSID, pythoncom.IID_IDispatch) # Must be a valid COM instance
  388. except pythoncom.com_error as details:
  389. import winerror
  390. # Some stupid objects fail here, even tho it is _already_ IDispatch!!??
  391. # Eg, Lotus notes.
  392. # So just let it use the existing object if E_NOINTERFACE
  393. if details.hresult != winerror.E_NOINTERFACE:
  394. raise
  395. oobj = oobj._oleobj_
  396. self.__dict__["_oleobj_"] = oobj # so we dont call __setattr__
  397. def __dir__(self):
  398. lst = list(self.__dict__.keys()) + dir(self.__class__) \
  399. + list(self._prop_map_get_.keys()) + list(self._prop_map_put_.keys())
  400. try: lst += [p.Name for p in self.Properties_]
  401. except AttributeError:
  402. pass
  403. return list(set(lst))
  404. # Provide a prettier name than the CLSID
  405. def __repr__(self):
  406. # Need to get the docstring for the module for this class.
  407. try:
  408. mod_doc = sys.modules[self.__class__.__module__].__doc__
  409. if mod_doc:
  410. mod_name = "win32com.gen_py." + mod_doc
  411. else:
  412. mod_name = sys.modules[self.__class__.__module__].__name__
  413. except KeyError:
  414. mod_name = "win32com.gen_py.unknown"
  415. return "<%s.%s instance at 0x%s>" % (mod_name, self.__class__.__name__, id(self))
  416. # Delegate comparison to the oleobjs, as they know how to do identity.
  417. def __eq__(self, other):
  418. other = getattr(other, "_oleobj_", other)
  419. return self._oleobj_ == other
  420. def __ne__(self, other):
  421. other = getattr(other, "_oleobj_", other)
  422. return self._oleobj_ != other
  423. def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
  424. return self._get_good_object_(
  425. self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
  426. user, resultCLSID)
  427. def __getattr__(self, attr):
  428. args=self._prop_map_get_.get(attr)
  429. if args is None:
  430. raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
  431. return self._ApplyTypes_(*args)
  432. def __setattr__(self, attr, value):
  433. if attr in self.__dict__: self.__dict__[attr] = value; return
  434. try:
  435. args, defArgs=self._prop_map_put_[attr]
  436. except KeyError:
  437. raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
  438. self._oleobj_.Invoke(*(args + (value,) + defArgs))
  439. def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None):
  440. return _get_good_single_object_(obj, obUserName, resultCLSID)
  441. def _get_good_object_(self, obj, obUserName=None, resultCLSID=None):
  442. return _get_good_object_(obj, obUserName, resultCLSID)
  443. # XXX - These should be consolidated with dynamic.py versions.
  444. def _get_good_single_object_(obj, obUserName=None, resultCLSID=None):
  445. if _PyIDispatchType==type(obj):
  446. return Dispatch(obj, obUserName, resultCLSID)
  447. return obj
  448. def _get_good_object_(obj, obUserName=None, resultCLSID=None):
  449. if obj is None:
  450. return None
  451. elif isinstance(obj, tuple):
  452. obUserNameTuple = (obUserName,) * len(obj)
  453. resultCLSIDTuple = (resultCLSID,) * len(obj)
  454. return tuple(map(_get_good_object_, obj, obUserNameTuple, resultCLSIDTuple))
  455. else:
  456. return _get_good_single_object_(obj, obUserName, resultCLSID)
  457. class CoClassBaseClass:
  458. def __init__(self, oobj=None):
  459. if oobj is None: oobj = pythoncom.new(self.CLSID)
  460. self.__dict__["_dispobj_"] = self.default_interface(oobj)
  461. def __repr__(self):
  462. return "<win32com.gen_py.%s.%s>" % (__doc__, self.__class__.__name__)
  463. def __getattr__(self, attr):
  464. d=self.__dict__["_dispobj_"]
  465. if d is not None: return getattr(d, attr)
  466. raise AttributeError(attr)
  467. def __setattr__(self, attr, value):
  468. if attr in self.__dict__: self.__dict__[attr] = value; return
  469. try:
  470. d=self.__dict__["_dispobj_"]
  471. if d is not None:
  472. d.__setattr__(attr, value)
  473. return
  474. except AttributeError:
  475. pass
  476. self.__dict__[attr] = value
  477. # Special methods don't use __getattr__ etc, so explicitly delegate here.
  478. # Some wrapped objects might not have them, but that's OK - the attribute
  479. # error can just bubble up.
  480. def __call__(self, *args, **kwargs):
  481. return self.__dict__["_dispobj_"].__call__(*args, **kwargs)
  482. def __str__(self, *args):
  483. return self.__dict__["_dispobj_"].__str__(*args)
  484. def __int__(self, *args):
  485. return self.__dict__["_dispobj_"].__int__(*args)
  486. def __iter__(self):
  487. return self.__dict__["_dispobj_"].__iter__()
  488. def __len__(self):
  489. return self.__dict__["_dispobj_"].__len__()
  490. def __nonzero__(self):
  491. return self.__dict__["_dispobj_"].__nonzero__()
  492. # A very simple VARIANT class. Only to be used with poorly-implemented COM
  493. # objects. If an object accepts an arg which is a simple "VARIANT", but still
  494. # is very pickly about the actual variant type (eg, isn't happy with a VT_I4,
  495. # which it would get from a Python integer), you can use this to force a
  496. # particular VT.
  497. class VARIANT(object):
  498. def __init__(self, vt, value):
  499. self.varianttype = vt
  500. self._value = value
  501. # 'value' is a property so when set by pythoncom it gets any magic wrapping
  502. # which normally happens for result objects
  503. def _get_value(self):
  504. return self._value
  505. def _set_value(self, newval):
  506. self._value = _get_good_object_(newval)
  507. def _del_value(self):
  508. del self._value
  509. value = property(_get_value, _set_value, _del_value)
  510. def __repr__(self):
  511. return "win32com.client.VARIANT(%r, %r)" % (self.varianttype, self._value)