Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add coroutine support for attribute listeners #979

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions dronekit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
----
"""

import sys
if sys.version_info >= (3, 4):
import asyncio
import collections
import copy
import logging
Expand Down Expand Up @@ -639,19 +642,34 @@ def notify_attribute_listeners(self, attr_name, value, cache=False):
return
self._attribute_cache[attr_name] = value

loop = None

# Notify observers.
for fn in self._attribute_listeners.get(attr_name, []):
try:
fn(self, attr_name, value)
if sys.version_info >= (3, 4) and asyncio.iscoroutinefunction(fn):
if loop is None:
loop = asyncio.new_event_loop()
loop.run_until_complete(fn(self, attr_name, value))
else:
fn(self, attr_name, value)
except Exception:
self._logger.exception('Exception in attribute handler for %s' % attr_name, exc_info=True)

for fn in self._attribute_listeners.get('*', []):
try:
fn(self, attr_name, value)
if sys.version_info >= (3, 4) and asyncio.iscoroutinefunction(fn):
if loop is None:
loop = asyncio.new_event_loop()
loop.run_until_complete(fn(self, attr_name, value))
else:
fn(self, attr_name, value)
except Exception:
self._logger.exception('Exception in attribute handler for %s' % attr_name, exc_info=True)

if loop is not None:
loop.close()

def on_attribute(self, name):
"""
Decorator for attribute listeners.
Expand Down