connection.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. # Copyright (C) 2007 Collabora Ltd. <http://www.collabora.co.uk/>
  2. #
  3. # Permission is hereby granted, free of charge, to any person
  4. # obtaining a copy of this software and associated documentation
  5. # files (the "Software"), to deal in the Software without
  6. # restriction, including without limitation the rights to use, copy,
  7. # modify, merge, publish, distribute, sublicense, and/or sell copies
  8. # of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be
  12. # included in all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  21. # DEALINGS IN THE SOFTWARE.
  22. __all__ = ('Connection', 'SignalMatch')
  23. __docformat__ = 'reStructuredText'
  24. import logging
  25. import threading
  26. import weakref
  27. from _dbus_bindings import (
  28. Connection as _Connection, LOCAL_IFACE, LOCAL_PATH, validate_bus_name,
  29. validate_interface_name, validate_member_name, validate_object_path)
  30. from dbus.exceptions import DBusException
  31. from dbus.lowlevel import (
  32. ErrorMessage, HANDLER_RESULT_NOT_YET_HANDLED, MethodCallMessage,
  33. MethodReturnMessage, SignalMessage)
  34. from dbus.proxies import ProxyObject
  35. from dbus._compat import is_py2, is_py3
  36. if is_py3:
  37. from _dbus_bindings import String
  38. else:
  39. from _dbus_bindings import UTF8String
  40. _logger = logging.getLogger('dbus.connection')
  41. def _noop(*args, **kwargs):
  42. pass
  43. class SignalMatch(object):
  44. _slots = ['_sender_name_owner', '_member', '_interface', '_sender',
  45. '_path', '_handler', '_args_match', '_rule',
  46. '_byte_arrays', '_conn_weakref',
  47. '_destination_keyword', '_interface_keyword',
  48. '_message_keyword', '_member_keyword',
  49. '_sender_keyword', '_path_keyword', '_int_args_match']
  50. if is_py2:
  51. _slots.append('_utf8_strings')
  52. __slots__ = tuple(_slots)
  53. def __init__(self, conn, sender, object_path, dbus_interface,
  54. member, handler, byte_arrays=False,
  55. sender_keyword=None, path_keyword=None,
  56. interface_keyword=None, member_keyword=None,
  57. message_keyword=None, destination_keyword=None,
  58. **kwargs):
  59. if member is not None:
  60. validate_member_name(member)
  61. if dbus_interface is not None:
  62. validate_interface_name(dbus_interface)
  63. if sender is not None:
  64. validate_bus_name(sender)
  65. if object_path is not None:
  66. validate_object_path(object_path)
  67. self._rule = None
  68. self._conn_weakref = weakref.ref(conn)
  69. self._sender = sender
  70. self._interface = dbus_interface
  71. self._member = member
  72. self._path = object_path
  73. self._handler = handler
  74. # if the connection is actually a bus, it's responsible for changing
  75. # this later
  76. self._sender_name_owner = sender
  77. if is_py2:
  78. self._utf8_strings = kwargs.pop('utf8_strings', False)
  79. elif 'utf8_strings' in kwargs:
  80. raise TypeError("unexpected keyword argument 'utf8_strings'")
  81. self._byte_arrays = byte_arrays
  82. self._sender_keyword = sender_keyword
  83. self._path_keyword = path_keyword
  84. self._member_keyword = member_keyword
  85. self._interface_keyword = interface_keyword
  86. self._message_keyword = message_keyword
  87. self._destination_keyword = destination_keyword
  88. self._args_match = kwargs
  89. if not kwargs:
  90. self._int_args_match = None
  91. else:
  92. self._int_args_match = {}
  93. for kwarg in kwargs:
  94. if not kwarg.startswith('arg'):
  95. raise TypeError('SignalMatch: unknown keyword argument %s'
  96. % kwarg)
  97. try:
  98. index = int(kwarg[3:])
  99. except ValueError:
  100. raise TypeError('SignalMatch: unknown keyword argument %s'
  101. % kwarg)
  102. if index < 0 or index > 63:
  103. raise TypeError('SignalMatch: arg match index must be in '
  104. 'range(64), not %d' % index)
  105. self._int_args_match[index] = kwargs[kwarg]
  106. def __hash__(self):
  107. """SignalMatch objects are compared by identity."""
  108. return hash(id(self))
  109. def __eq__(self, other):
  110. """SignalMatch objects are compared by identity."""
  111. return self is other
  112. def __ne__(self, other):
  113. """SignalMatch objects are compared by identity."""
  114. return self is not other
  115. sender = property(lambda self: self._sender)
  116. def __str__(self):
  117. if self._rule is None:
  118. rule = ["type='signal'"]
  119. if self._sender is not None:
  120. rule.append("sender='%s'" % self._sender)
  121. if self._path is not None:
  122. rule.append("path='%s'" % self._path)
  123. if self._interface is not None:
  124. rule.append("interface='%s'" % self._interface)
  125. if self._member is not None:
  126. rule.append("member='%s'" % self._member)
  127. if self._int_args_match is not None:
  128. for index, value in self._int_args_match.items():
  129. rule.append("arg%d='%s'" % (index, value))
  130. self._rule = ','.join(rule)
  131. return self._rule
  132. def __repr__(self):
  133. return ('<%s at %x "%s" on conn %r>'
  134. % (self.__class__, id(self), self._rule, self._conn_weakref()))
  135. def set_sender_name_owner(self, new_name):
  136. self._sender_name_owner = new_name
  137. def matches_removal_spec(self, sender, object_path,
  138. dbus_interface, member, handler, **kwargs):
  139. if handler not in (None, self._handler):
  140. return False
  141. if sender != self._sender:
  142. return False
  143. if object_path != self._path:
  144. return False
  145. if dbus_interface != self._interface:
  146. return False
  147. if member != self._member:
  148. return False
  149. if kwargs != self._args_match:
  150. return False
  151. return True
  152. def maybe_handle_message(self, message):
  153. args = None
  154. # these haven't been checked yet by the match tree
  155. if self._sender_name_owner not in (None, message.get_sender()):
  156. return False
  157. if self._int_args_match is not None:
  158. # extracting args with utf8_strings and byte_arrays is less work
  159. kwargs = dict(byte_arrays=True)
  160. arg_type = (String if is_py3 else UTF8String)
  161. if is_py2:
  162. kwargs['utf8_strings'] = True
  163. args = message.get_args_list(**kwargs)
  164. for index, value in self._int_args_match.items():
  165. if (index >= len(args)
  166. or not isinstance(args[index], arg_type)
  167. or args[index] != value):
  168. return False
  169. # these have likely already been checked by the match tree
  170. if self._member not in (None, message.get_member()):
  171. return False
  172. if self._interface not in (None, message.get_interface()):
  173. return False
  174. if self._path not in (None, message.get_path()):
  175. return False
  176. try:
  177. # minor optimization: if we already extracted the args with the
  178. # right calling convention to do the args match, don't bother
  179. # doing so again
  180. utf8_strings = (is_py2 and self._utf8_strings)
  181. if args is None or not utf8_strings or not self._byte_arrays:
  182. kwargs = dict(byte_arrays=self._byte_arrays)
  183. if is_py2:
  184. kwargs['utf8_strings'] = self._utf8_strings
  185. args = message.get_args_list(**kwargs)
  186. kwargs = {}
  187. if self._sender_keyword is not None:
  188. kwargs[self._sender_keyword] = message.get_sender()
  189. if self._destination_keyword is not None:
  190. kwargs[self._destination_keyword] = message.get_destination()
  191. if self._path_keyword is not None:
  192. kwargs[self._path_keyword] = message.get_path()
  193. if self._member_keyword is not None:
  194. kwargs[self._member_keyword] = message.get_member()
  195. if self._interface_keyword is not None:
  196. kwargs[self._interface_keyword] = message.get_interface()
  197. if self._message_keyword is not None:
  198. kwargs[self._message_keyword] = message
  199. self._handler(*args, **kwargs)
  200. except:
  201. # basicConfig is a no-op if logging is already configured
  202. logging.basicConfig()
  203. _logger.error('Exception in handler for D-Bus signal:', exc_info=1)
  204. return True
  205. def remove(self):
  206. conn = self._conn_weakref()
  207. # do nothing if the connection has already vanished
  208. if conn is not None:
  209. conn.remove_signal_receiver(self, self._member,
  210. self._interface, self._sender,
  211. self._path,
  212. **self._args_match)
  213. class Connection(_Connection):
  214. """A connection to another application. In this base class there is
  215. assumed to be no bus daemon.
  216. :Since: 0.81.0
  217. """
  218. ProxyObjectClass = ProxyObject
  219. def __init__(self, *args, **kwargs):
  220. super(Connection, self).__init__(*args, **kwargs)
  221. # this if-block is needed because shared bus connections can be
  222. # __init__'ed more than once
  223. if not hasattr(self, '_dbus_Connection_initialized'):
  224. self._dbus_Connection_initialized = 1
  225. self.__call_on_disconnection = []
  226. self._signal_recipients_by_object_path = {}
  227. """Map from object path to dict mapping dbus_interface to dict
  228. mapping member to list of SignalMatch objects."""
  229. self._signals_lock = threading.Lock()
  230. """Lock used to protect signal data structures"""
  231. self.add_message_filter(self.__class__._signal_func)
  232. def activate_name_owner(self, bus_name):
  233. """Return the unique name for the given bus name, activating it
  234. if necessary and possible.
  235. If the name is already unique or this connection is not to a
  236. bus daemon, just return it.
  237. :Returns: a bus name. If the given `bus_name` exists, the returned
  238. name identifies its current owner; otherwise the returned name
  239. does not exist.
  240. :Raises DBusException: if the implementation has failed
  241. to activate the given bus name.
  242. :Since: 0.81.0
  243. """
  244. return bus_name
  245. def get_object(self, bus_name=None, object_path=None, introspect=True,
  246. **kwargs):
  247. """Return a local proxy for the given remote object.
  248. Method calls on the proxy are translated into method calls on the
  249. remote object.
  250. :Parameters:
  251. `bus_name` : str
  252. A bus name (either the unique name or a well-known name)
  253. of the application owning the object. The keyword argument
  254. named_service is a deprecated alias for this.
  255. `object_path` : str
  256. The object path of the desired object
  257. `introspect` : bool
  258. If true (default), attempt to introspect the remote
  259. object to find out supported methods and their signatures
  260. :Returns: a `dbus.proxies.ProxyObject`
  261. """
  262. named_service = kwargs.pop('named_service', None)
  263. if named_service is not None:
  264. if bus_name is not None:
  265. raise TypeError('bus_name and named_service cannot both '
  266. 'be specified')
  267. from warnings import warn
  268. warn('Passing the named_service parameter to get_object by name '
  269. 'is deprecated: please use positional parameters',
  270. DeprecationWarning, stacklevel=2)
  271. bus_name = named_service
  272. if kwargs:
  273. raise TypeError('get_object does not take these keyword '
  274. 'arguments: %s' % ', '.join(kwargs.keys()))
  275. return self.ProxyObjectClass(self, bus_name, object_path,
  276. introspect=introspect)
  277. def add_signal_receiver(self, handler_function,
  278. signal_name=None,
  279. dbus_interface=None,
  280. bus_name=None,
  281. path=None,
  282. **keywords):
  283. """Arrange for the given function to be called when a signal matching
  284. the parameters is received.
  285. :Parameters:
  286. `handler_function` : callable
  287. The function to be called. Its positional arguments will
  288. be the arguments of the signal. By default it will receive
  289. no keyword arguments, but see the description of
  290. the optional keyword arguments below.
  291. `signal_name` : str
  292. The signal name; None (the default) matches all names
  293. `dbus_interface` : str
  294. The D-Bus interface name with which to qualify the signal;
  295. None (the default) matches all interface names
  296. `bus_name` : str
  297. A bus name for the sender, which will be resolved to a
  298. unique name if it is not already; None (the default) matches
  299. any sender.
  300. `path` : str
  301. The object path of the object which must have emitted the
  302. signal; None (the default) matches any object path
  303. :Keywords:
  304. `utf8_strings` : bool
  305. If True, the handler function will receive any string
  306. arguments as dbus.UTF8String objects (a subclass of str
  307. guaranteed to be UTF-8). If False (default) it will receive
  308. any string arguments as dbus.String objects (a subclass of
  309. unicode).
  310. `byte_arrays` : bool
  311. If True, the handler function will receive any byte-array
  312. arguments as dbus.ByteArray objects (a subclass of str).
  313. If False (default) it will receive any byte-array
  314. arguments as a dbus.Array of dbus.Byte (subclasses of:
  315. a list of ints).
  316. `sender_keyword` : str
  317. If not None (the default), the handler function will receive
  318. the unique name of the sending endpoint as a keyword
  319. argument with this name.
  320. `destination_keyword` : str
  321. If not None (the default), the handler function will receive
  322. the bus name of the destination (or None if the signal is a
  323. broadcast, as is usual) as a keyword argument with this name.
  324. `interface_keyword` : str
  325. If not None (the default), the handler function will receive
  326. the signal interface as a keyword argument with this name.
  327. `member_keyword` : str
  328. If not None (the default), the handler function will receive
  329. the signal name as a keyword argument with this name.
  330. `path_keyword` : str
  331. If not None (the default), the handler function will receive
  332. the object-path of the sending object as a keyword argument
  333. with this name.
  334. `message_keyword` : str
  335. If not None (the default), the handler function will receive
  336. the `dbus.lowlevel.SignalMessage` as a keyword argument with
  337. this name.
  338. `arg...` : unicode or UTF-8 str
  339. If there are additional keyword parameters of the form
  340. ``arg``\ *n*, match only signals where the *n*\ th argument
  341. is the value given for that keyword parameter. As of this
  342. time only string arguments can be matched (in particular,
  343. object paths and signatures can't).
  344. `named_service` : str
  345. A deprecated alias for `bus_name`.
  346. """
  347. self._require_main_loop()
  348. named_service = keywords.pop('named_service', None)
  349. if named_service is not None:
  350. if bus_name is not None:
  351. raise TypeError('bus_name and named_service cannot both be '
  352. 'specified')
  353. bus_name = named_service
  354. from warnings import warn
  355. warn('Passing the named_service parameter to add_signal_receiver '
  356. 'by name is deprecated: please use positional parameters',
  357. DeprecationWarning, stacklevel=2)
  358. match = SignalMatch(self, bus_name, path, dbus_interface,
  359. signal_name, handler_function, **keywords)
  360. self._signals_lock.acquire()
  361. try:
  362. by_interface = self._signal_recipients_by_object_path.setdefault(
  363. path, {})
  364. by_member = by_interface.setdefault(dbus_interface, {})
  365. matches = by_member.setdefault(signal_name, [])
  366. matches.append(match)
  367. finally:
  368. self._signals_lock.release()
  369. return match
  370. def _iter_easy_matches(self, path, dbus_interface, member):
  371. if path is not None:
  372. path_keys = (None, path)
  373. else:
  374. path_keys = (None,)
  375. if dbus_interface is not None:
  376. interface_keys = (None, dbus_interface)
  377. else:
  378. interface_keys = (None,)
  379. if member is not None:
  380. member_keys = (None, member)
  381. else:
  382. member_keys = (None,)
  383. for path in path_keys:
  384. by_interface = self._signal_recipients_by_object_path.get(path)
  385. if by_interface is None:
  386. continue
  387. for dbus_interface in interface_keys:
  388. by_member = by_interface.get(dbus_interface, None)
  389. if by_member is None:
  390. continue
  391. for member in member_keys:
  392. matches = by_member.get(member, None)
  393. if matches is None:
  394. continue
  395. for m in matches:
  396. yield m
  397. def remove_signal_receiver(self, handler_or_match,
  398. signal_name=None,
  399. dbus_interface=None,
  400. bus_name=None,
  401. path=None,
  402. **keywords):
  403. named_service = keywords.pop('named_service', None)
  404. if named_service is not None:
  405. if bus_name is not None:
  406. raise TypeError('bus_name and named_service cannot both be '
  407. 'specified')
  408. bus_name = named_service
  409. from warnings import warn
  410. warn('Passing the named_service parameter to '
  411. 'remove_signal_receiver by name is deprecated: please use '
  412. 'positional parameters',
  413. DeprecationWarning, stacklevel=2)
  414. new = []
  415. deletions = []
  416. self._signals_lock.acquire()
  417. try:
  418. by_interface = self._signal_recipients_by_object_path.get(path,
  419. None)
  420. if by_interface is None:
  421. return
  422. by_member = by_interface.get(dbus_interface, None)
  423. if by_member is None:
  424. return
  425. matches = by_member.get(signal_name, None)
  426. if matches is None:
  427. return
  428. for match in matches:
  429. if (handler_or_match is match
  430. or match.matches_removal_spec(bus_name,
  431. path,
  432. dbus_interface,
  433. signal_name,
  434. handler_or_match,
  435. **keywords)):
  436. deletions.append(match)
  437. else:
  438. new.append(match)
  439. if new:
  440. by_member[signal_name] = new
  441. else:
  442. del by_member[signal_name]
  443. if not by_member:
  444. del by_interface[dbus_interface]
  445. if not by_interface:
  446. del self._signal_recipients_by_object_path[path]
  447. finally:
  448. self._signals_lock.release()
  449. for match in deletions:
  450. self._clean_up_signal_match(match)
  451. def _clean_up_signal_match(self, match):
  452. # Now called without the signals lock held (it was held in <= 0.81.0)
  453. pass
  454. def _signal_func(self, message):
  455. """D-Bus filter function. Handle signals by dispatching to Python
  456. callbacks kept in the match-rule tree.
  457. """
  458. if not isinstance(message, SignalMessage):
  459. return HANDLER_RESULT_NOT_YET_HANDLED
  460. dbus_interface = message.get_interface()
  461. path = message.get_path()
  462. signal_name = message.get_member()
  463. for match in self._iter_easy_matches(path, dbus_interface,
  464. signal_name):
  465. match.maybe_handle_message(message)
  466. if (dbus_interface == LOCAL_IFACE and
  467. path == LOCAL_PATH and
  468. signal_name == 'Disconnected'):
  469. for cb in self.__call_on_disconnection:
  470. try:
  471. cb(self)
  472. except Exception:
  473. # basicConfig is a no-op if logging is already configured
  474. logging.basicConfig()
  475. _logger.error('Exception in handler for Disconnected '
  476. 'signal:', exc_info=1)
  477. return HANDLER_RESULT_NOT_YET_HANDLED
  478. def call_async(self, bus_name, object_path, dbus_interface, method,
  479. signature, args, reply_handler, error_handler,
  480. timeout=-1.0, byte_arrays=False,
  481. require_main_loop=True, **kwargs):
  482. """Call the given method, asynchronously.
  483. If the reply_handler is None, successful replies will be ignored.
  484. If the error_handler is None, failures will be ignored. If both
  485. are None, the implementation may request that no reply is sent.
  486. :Returns: The dbus.lowlevel.PendingCall.
  487. :Since: 0.81.0
  488. """
  489. if object_path == LOCAL_PATH:
  490. raise DBusException('Methods may not be called on the reserved '
  491. 'path %s' % LOCAL_PATH)
  492. if dbus_interface == LOCAL_IFACE:
  493. raise DBusException('Methods may not be called on the reserved '
  494. 'interface %s' % LOCAL_IFACE)
  495. # no need to validate other args - MethodCallMessage ctor will do
  496. get_args_opts = dict(byte_arrays=byte_arrays)
  497. if is_py2:
  498. get_args_opts['utf8_strings'] = kwargs.get('utf8_strings', False)
  499. elif 'utf8_strings' in kwargs:
  500. raise TypeError("unexpected keyword argument 'utf8_strings'")
  501. message = MethodCallMessage(destination=bus_name,
  502. path=object_path,
  503. interface=dbus_interface,
  504. method=method)
  505. # Add the arguments to the function
  506. try:
  507. message.append(signature=signature, *args)
  508. except Exception as e:
  509. logging.basicConfig()
  510. _logger.error('Unable to set arguments %r according to '
  511. 'signature %r: %s: %s',
  512. args, signature, e.__class__, e)
  513. raise
  514. if reply_handler is None and error_handler is None:
  515. # we don't care what happens, so just send it
  516. self.send_message(message)
  517. return
  518. if reply_handler is None:
  519. reply_handler = _noop
  520. if error_handler is None:
  521. error_handler = _noop
  522. def msg_reply_handler(message):
  523. if isinstance(message, MethodReturnMessage):
  524. reply_handler(*message.get_args_list(**get_args_opts))
  525. elif isinstance(message, ErrorMessage):
  526. error_handler(DBusException(name=message.get_error_name(),
  527. *message.get_args_list()))
  528. else:
  529. error_handler(TypeError('Unexpected type for reply '
  530. 'message: %r' % message))
  531. return self.send_message_with_reply(message, msg_reply_handler,
  532. timeout,
  533. require_main_loop=require_main_loop)
  534. def call_blocking(self, bus_name, object_path, dbus_interface, method,
  535. signature, args, timeout=-1.0,
  536. byte_arrays=False, **kwargs):
  537. """Call the given method, synchronously.
  538. :Since: 0.81.0
  539. """
  540. if object_path == LOCAL_PATH:
  541. raise DBusException('Methods may not be called on the reserved '
  542. 'path %s' % LOCAL_PATH)
  543. if dbus_interface == LOCAL_IFACE:
  544. raise DBusException('Methods may not be called on the reserved '
  545. 'interface %s' % LOCAL_IFACE)
  546. # no need to validate other args - MethodCallMessage ctor will do
  547. get_args_opts = dict(byte_arrays=byte_arrays)
  548. if is_py2:
  549. get_args_opts['utf8_strings'] = kwargs.get('utf8_strings', False)
  550. elif 'utf8_strings' in kwargs:
  551. raise TypeError("unexpected keyword argument 'utf8_strings'")
  552. message = MethodCallMessage(destination=bus_name,
  553. path=object_path,
  554. interface=dbus_interface,
  555. method=method)
  556. # Add the arguments to the function
  557. try:
  558. message.append(signature=signature, *args)
  559. except Exception as e:
  560. logging.basicConfig()
  561. _logger.error('Unable to set arguments %r according to '
  562. 'signature %r: %s: %s',
  563. args, signature, e.__class__, e)
  564. raise
  565. # make a blocking call
  566. reply_message = self.send_message_with_reply_and_block(
  567. message, timeout)
  568. args_list = reply_message.get_args_list(**get_args_opts)
  569. if len(args_list) == 0:
  570. return None
  571. elif len(args_list) == 1:
  572. return args_list[0]
  573. else:
  574. return tuple(args_list)
  575. def call_on_disconnection(self, callable):
  576. """Arrange for `callable` to be called with one argument (this
  577. Connection object) when the Connection becomes
  578. disconnected.
  579. :Since: 0.83.0
  580. """
  581. self.__call_on_disconnection.append(callable)