Repository: XKNX/xknx
Pull request #939 (2022-05-01 20:11:39)

Rename Task `task` attribute to `async_func`
<!--
  You are awesome! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template!.
-->
## Description
<!--
Please include a summary of the change and which issue is fixed.
Please also include relevant motivation and context.
List any dependencies that are required for this change.
-->
- Rename TaskRegistry.register and Task `task` attribute to `async_func` to avoid confusion
- Return Task from `start()`

Fixes # (issue)

## Type of change
<!--
Please tick the applicable options.
NOTE: Ticking multiple options most likely indicates
that your change is to big and it is suggested to split it into several smaller PRs.
-->

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] This change requires a documentation update

## Checklist:

- [ ] I have performed a self-review of my own code
- [ ] The documentation has been adjusted accordingly
- [ ] The changes generate no new warnings
- [ ] Tests have been added that prove the fix is effective or that the feature works
- [ ] The changes are documented in the changelog
- [ ] The Homeassistant plugin has been adjusted in case of new config options


codecov[bot]: # [Codecov](https://codecov.io/gh/XKNX/xknx/pull/939?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX) Report
> Merging [#939](https://codecov.io/gh/XKNX/xknx/pull/939?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX) (a6c952a) into [main](https://codecov.io/gh/XKNX/xknx/commit/1a4c7b8a5a78488db7fd56cb0e6eb1af10c66fdc?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX) (1a4c7b8) will **decrease** coverage by `0.00%`.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/XKNX/xknx/pull/939/graphs/tree.svg?width=650&height=150&src=pr&token=irWbIygS84&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX)](https://codecov.io/gh/XKNX/xknx/pull/939?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX)

```diff
@@            Coverage Diff             @@
##             main     #939      +/-   ##
==========================================
- Coverage   95.96%   95.96%   -0.01%     
==========================================
  Files         130      130              
  Lines        7781     7777       -4     
==========================================
- Hits         7467     7463       -4     
  Misses        314      314              
```


| [Impacted Files](https://codecov.io/gh/XKNX/xknx/pull/939?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX) | Coverage Δ | |
|---|---|---|
| [xknx/devices/binary\_sensor.py](https://codecov.io/gh/XKNX/xknx/pull/939/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX#diff-eGtueC9kZXZpY2VzL2JpbmFyeV9zZW5zb3IucHk=) | `98.90% <ø> (-0.03%)` | :arrow_down: |
| [xknx/devices/light.py](https://codecov.io/gh/XKNX/xknx/pull/939/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX#diff-eGtueC9kZXZpY2VzL2xpZ2h0LnB5) | `99.60% <ø> (ø)` | |
| [xknx/devices/switch.py](https://codecov.io/gh/XKNX/xknx/pull/939/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX#diff-eGtueC9kZXZpY2VzL3N3aXRjaC5weQ==) | `100.00% <ø> (ø)` | |
| [xknx/core/task\_registry.py](https://codecov.io/gh/XKNX/xknx/pull/939/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX#diff-eGtueC9jb3JlL3Rhc2tfcmVnaXN0cnkucHk=) | `100.00% <100.00%> (ø)` | |
| [xknx/devices/datetime.py](https://codecov.io/gh/XKNX/xknx/pull/939/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=XKNX#diff-eGtueC9kZXZpY2VzL2RhdGV0aW1lLnB5) | `95.00% <100.00%> (-0.24%)` | :arrow_down: |

marvin-w: Cool!

Patch:
diff --git a/changelog.md b/changelog.md
index 525fd535..df08a4ce 100644
--- a/changelog.md
+++ b/changelog.md
@@ -2,6 +2,10 @@
 
 ## Unreleased changes
 
+### Internals
+
+- Rename TaskRegistry.register and Task `task` attribute to `async_func` to avoid confusion; return Task from `start()`
+
 ## 0.21.1 Fix Task Registry 2022-05-01
 
 ### Bugfixes
diff --git a/xknx/core/task_registry.py b/xknx/core/task_registry.py
index f306adfb..6221bc8b 100644
--- a/xknx/core/task_registry.py
+++ b/xknx/core/task_registry.py
@@ -21,18 +21,19 @@ class Task:
     def __init__(
         self,
         name: str,
-        task: AsyncCallbackType,
+        async_func: AsyncCallbackType,
         restart_after_reconnect: bool = False,
     ) -> None:
         """Initialize Task class."""
         self.name = name
-        self.task = task
+        self.async_func = async_func
         self.restart_after_reconnect = restart_after_reconnect
         self._task: asyncio.Task[None] | None = None
 
-    def start(self) -> None:
+    def start(self) -> Task:
         """Start a task."""
-        self._task = asyncio.create_task(self.task(), name=self.name)
+        self._task = asyncio.create_task(self.async_func(), name=self.name)
+        return self
 
     def __await__(self) -> Generator[None, None, None]:
         """Wait for task to be finished."""
@@ -72,7 +73,7 @@ class TaskRegistry:
     def register(
         self,
         name: str,
-        task: AsyncCallbackType,
+        async_func: AsyncCallbackType,
         track_task: bool = True,
         restart_after_reconnect: bool = False,
     ) -> Task:
@@ -80,7 +81,9 @@ class TaskRegistry:
         self.unregister(name)
 
         _task: Task = Task(
-            name=name, task=task, restart_after_reconnect=restart_after_reconnect
+            name=name,
+            async_func=async_func,
+            restart_after_reconnect=restart_after_reconnect,
         )
 
         if track_task:
diff --git a/xknx/devices/binary_sensor.py b/xknx/devices/binary_sensor.py
index d8813241..d8539c06 100644
--- a/xknx/devices/binary_sensor.py
+++ b/xknx/devices/binary_sensor.py
@@ -94,9 +94,8 @@ class BinarySensor(Device):
                 self.bump_and_get_counter(state)
                 self._context_task = self.xknx.task_registry.register(
                     name=self._context_task_name,
-                    task=partial(self._counter_task, self._context_timeout),
-                )
-                self._context_task.start()
+                    async_func=partial(self._counter_task, self._context_timeout),
+                ).start()
             else:
                 await self.after_update()
 
@@ -159,10 +158,9 @@ class BinarySensor(Device):
         if self.reset_after is not None and self.state:
             self._reset_task = self.xknx.task_registry.register(
                 name=self._reset_task_name,
-                task=partial(self._reset_state, self.reset_after),
+                async_func=partial(self._reset_state, self.reset_after),
                 track_task=True,
-            )
-            self._reset_task.start()
+            ).start()
 
     async def _reset_state(self, wait_seconds: float) -> None:
         await asyncio.sleep(wait_seconds)
diff --git a/xknx/devices/datetime.py b/xknx/devices/datetime.py
index a18737d8..12ec89a0 100644
--- a/xknx/devices/datetime.py
+++ b/xknx/devices/datetime.py
@@ -65,13 +65,11 @@ class DateTime(Device):
                 await asyncio.sleep(minutes * 60)
 
         if self.localtime:
-            task: Task = self.xknx.task_registry.register(
+            return self.xknx.task_registry.register(
                 name=f"datetime.broadcast_{id(self)}",
-                task=partial(broadcast_loop, self, minutes),
+                async_func=partial(broadcast_loop, self, minutes),
                 restart_after_reconnect=True,
-            )
-            task.start()
-            return task
+            ).start()
         return None
 
     async def broadcast_localtime(self, response: bool = False) -> None:
diff --git a/xknx/devices/light.py b/xknx/devices/light.py
index a1549f5d..42e0f0a2 100644
--- a/xknx/devices/light.py
+++ b/xknx/devices/light.py
@@ -369,7 +369,7 @@ class Light(Device):
             # task registry cancels existing task
             self.xknx.task_registry.register(
                 name=self._individual_color_debounce_task_name,
-                task=debouncer,
+                async_func=debouncer,
             ).start()
             return
         self.xknx.task_registry.unregister(self._individual_color_debounce_task_name)
diff --git a/xknx/devices/switch.py b/xknx/devices/switch.py
index fed84fd6..4152ced7 100644
--- a/xknx/devices/switch.py
+++ b/xknx/devices/switch.py
@@ -89,10 +89,9 @@ class Switch(Device):
             if self.reset_after is not None and self.switch.value:
                 self._reset_task = self.xknx.task_registry.register(
                     name=self._reset_task_name,
-                    task=partial(self._reset_state, self.reset_after),
+                    async_func=partial(self._reset_state, self.reset_after),
                     track_task=True,
-                )
-                self._reset_task.start()
+                ).start()
 
     async def process_group_read(self, telegram: "Telegram") -> None:
         """Process incoming GroupValueResponse telegrams."""


Test patch:
diff --git a/test/core_tests/task_registry_test.py b/test/core_tests/task_registry_test.py
index 7c4b83e5..66a0cc48 100644
--- a/test/core_tests/task_registry_test.py
+++ b/test/core_tests/task_registry_test.py
@@ -22,7 +22,7 @@ class TestTaskRegistry:
 
         task = xknx.task_registry.register(
             name="test",
-            task=callback,
+            async_func=callback,
         )
         assert len(xknx.task_registry.tasks) == 1
         task.start()
@@ -39,7 +39,7 @@ class TestTaskRegistry:
 
         task = xknx.task_registry.register(
             name="test",
-            task=callback,
+            async_func=callback,
         )
         assert len(xknx.task_registry.tasks) == 1
         task.start()
@@ -60,7 +60,7 @@ class TestTaskRegistry:
 
         task = xknx.task_registry.register(
             name="test",
-            task=callback,
+            async_func=callback,
         )
         assert len(xknx.task_registry.tasks) == 1
         task.start()
@@ -92,7 +92,7 @@ class TestTaskRegistry:
                 self.test -= 1
 
         task = xknx.task_registry.register(
-            name="test", task=callback, restart_after_reconnect=True
+            name="test", async_func=callback, restart_after_reconnect=True
         )
         assert len(xknx.task_registry.tasks) == 1
         task.start()