Python3 type hint for operator module

Viewed 753

How can I write a type hint for an argument that should be an operator function? For example, see this function:

import operator
from typing import Dict, Tuple

def func(thresholds: Dict[str, Tuple[operator, float]] = None):
    if thresholds is None:
        thresholds = {"height": (operator.lt, 0.7), "width": (operator.gt, 0.1)}
    pass

When I try to run my code I get:

TypeError: Tuple[t0, t1, ...]: each t must be a type. Got <module 'operator' from ...>.

Edit: I realize that operator is a module, not a type, and that the argument I'm looking for is a function from that module. I'm trying to see if there's any way to let the user know that I expect an operator function as the argument. Is the only way to explain in a docstring?

1 Answers

operator is a module, not a class or type. What you want to do is make a typehint that can satisfy the functions being passes to func. If we were to write operator.lt from scratch, it would probably look like this:

from numbers import Number

def le(a: Number, b: Number) -> bool:
    ...

Using the Callable type we can write this as:

Callable[[Number, Number], bool]

Putting that altogether you would get something like this:

import operator
from typing import Dict, Tuple, Callable, Optional
from numbers import Number


Operator = Callable[[Number, Number], bool]
OperatorDict = Dict[str, Tuple[Operator, float]]


def func(thresholds: Optional[OperatorDict] = None) -> None:
    if thresholds is None:
        thresholds = {"height": (operator.lt, 0.7), "width": (operator.gt, 0.1)}
    pass
Related