py_trees icon indicating copy to clipboard operation
py_trees copied to clipboard

ComparisonExpression could probably use Generics

Open jbcpollak opened this issue 3 years ago • 0 comments

I think ComparisonExpression could benefit from generics to improve type specificity. What happens now is that because operator is declared to take two Anys, mypy returns:

error: Returning Any from function declared to return "Behaviour"

for a lot of common use cases, because the variable and value are both Any.

I think defining the class like so might help (I can try and test in the future, just wanted to flag it now):

T_contra = TypeVar('T_contra', contravariant=True)  # contravariant.
V_contra = TypeVar('V_contra', contravariant=True)  # contravariant.

class ComparisonExpression(Generic[T_contra, V_contra]):
    """
    Store the parameters for a univariate comparison operation
    (i.e. between a variable and a value).

    Args:
        variable: name of the variable to compare
        value: value to compare against
        operator: a callable comparison operator

    .. tip::
        The python `operator module`_ includes many useful comparison operations, e.g. operator.ne
    """
    def __init__(
        self,
        variable: str,
        value: V,
        operator: typing.Callable[[T_contra, V_contra], bool]
    ):
        self.variable = variable
        self.value = value
        self.operator = operator

I haven't tested the above, but it should work. The contravariant part may not be strictly necessary but if users have cases where "variable" or value is sometimes a child type of the declared ComparisonExpression, it would be helpful.

jbcpollak avatar Jun 01 '21 15:06 jbcpollak