Splitting rule file

I have two rules M and T which uses the same functionality in the background. This is made in the classes MH and TH. They are also rules as they also use the functionality of rules. MH and TH are identical, but need to be different instances.
They are implemented in the same file as the calling rule (M and MH, T and TH). See abstract example below.

As MH and TH are identical I would like to separate them in another file. Usually I would place it in the lib folder and import that rule class, but the documentation states not to do so:

    lib: lib        # Custom modules, libraries and files can be placed there.
                    # (!) Attention (!):
                    # Don't create rule instances in files inside the lib folder! It will lead to strange behaviour.

Example of M and MH:

from typing import Awaitable, Callable
from HABApp import Rule

class MH(Rule):
    def __init__(
        ItemName1: str,
        ItemName2: str,
        ExecFunction: Callable[[str, str, str], Awaitable[bool]],
    ) -> None:

class M(Rule):
    def __init__(self) -> None:
        self.MBH: MH = MH("ItemName1", "ItemName2", self.ExecFunction)

    async def ExecFunction(
        self, Par1: str, Par2: str, Par3: str
    ) -> bool:
        return False

I tried some variants to call MH when it is implemented in its own rule file, but always failed. What is the right way to achieve this?

You can put the rule definition in the lib folder but create the instance in the rule file.
Note the difference between definition and rule instance creation.
Be aware that by putting the file in the lib folder you will have to restart habapp to reload the functionality.

But imho it’s way easier to just use a HABApp internal item to achieve the same:
You can post a str tuple to the item and then run the functionality of M based on a rule with an item listener.

Thanks for the suggestions. I will give it a try!

I’ve implemented the second variant and it helped me deduplicating the code :slight_smile:! As the function had a return code I needed twice this mechanism with the item.
The first variant I haven’t fully understood and therefor I didn’t get it to work. Could you provide an example how this should work?