How to type-hint "SupportsOrdering" in a function parameter?

rdas

I'm trying to implement a function that inverses a strictly monotonically increasing function. Given a value y and a strictly monotonically increasing function f, the function I'm trying to write would calculate f_inverse(y) & return that.

Ideally this should work for any argument-set that has a total ordering defined on it. So it should work for int, float, tuple etc.

So far I have this:

def invert_strictly_monotonic_function(y: Any, f: Callable[[Any], Any]) -> Any:
    pass

I would like to replace the Any with something like "SupportsOrdering" - that would tell me that I could rely on the __eq__ & __lt__ methods inside this function.

But, of course, SupportsOrdering doesn't exist in the typing module.

So, how do I go about type-hinting this? Do I need to define my own protocol-type for this? And how would I make that work with something like @total_ordering?

Niel Godfrey Ponciano

Since the typing module doesn't provide a comparable type, I think an alternative is defining our own custom type with the use of typing.protocol as the base class (for structural subtyping) requiring the comparer methods e.g. __lt__ and __eq__ with a user-defined SupportsOrdering, inspired by these list of pre-defined protocols e.g. typing.SupportsRound.

User-defined comparable type:

from __future__ import annotations

from abc import abstractmethod
from typing import Protocol, runtime_checkable, TypeVar


@runtime_checkable
class Comparable(Protocol):
    @abstractmethod
    def __lt__(self: SupportsOrdering, other: SupportsOrdering) -> bool:
        pass

    @abstractmethod
    def __eq__(self: SupportsOrdering, other: object) -> bool:
        pass


SupportsOrdering = TypeVar("SupportsOrdering", bound=Comparable)

Funcionality to test the comparable type:

class MyNonComparableClass:
    def __init__(self, data):
        self.data = data


class MyComparableClass:
    def __init__(self, data):
        self.data = data

    def __lt__(self: MyComparableClass, other: MyComparableClass) -> bool:
        return self.data < other.data

    def __eq__(self: MyComparableClass, other: object) -> bool:
        if not isinstance(other, MyComparableClass):
            return NotImplemented
        return self.data == other.data


def func(value: SupportsOrdering) -> SupportsOrdering:
    return value

Test 1: Comparable types

# Comparable built-ins
func(True)
func(1)
func(1.2)
func("a")
func("abc")
func([1, 2, 3])  # Sequence objects typically may be compared https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types
func((1, 2, 3))
func({1, 2, 3})

# Comparable user-defined class
func(MyComparableClass(1))

Output:

$ mypy script.py  # Install mypy via <python3 -m pip install mypy>
Success: no issues found in 1 source file

Test 2: Non-comparable types

# Non-comparable built-ins
func({"1": "1"})  # Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError. https://docs.python.org/3/library/stdtypes.html#mapping-types-dict

# Non-comparable user-defined class
func(MyNonComparableClass(1))

Output:

$ mypy script.py  # Install mypy via <python3 -m pip install mypy>
script.py:57: error: Value of type variable "SupportsOrdering" of "func" cannot be "Dict[str, str]"
script.py:60: error: Value of type variable "SupportsOrdering" of "func" cannot be "MyNonComparableClass"

References:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to type hint a function's optional return parameter?

How to reference the type hint of a function

How to type-hint generic as a parameter in TypeScript?

How to type hint that a function returns another function?

How to type hint a function that returns a function?

Custom type hint with parameter

How do I type hint a filename in a function?

How to hint the type of a function I do not control?

How to type hint a function that transforms an RDD?

How to type hint specific objects in function argument

Abstract function parameter type hint overriding in PHP 7

What is the type hint for a function

How to type hint function accepting both union and any type of that union?

How do you hint different options for a function's object parameter?

How to type-hint non-basic parameters of a function?

Python - how to type hint calling a function that returns a tuple?

How do I type hint a function that returns an instance of the current class?

In Python 3.5, how can I specify a function as a type hint?

How to provide type hint for a function that returns an Protocol subclass in Python?

How to type hint function with a callable argument and default value

Change type of member parameter for python type hint

Type hint that a function never returns

Is it possible to type hint a lambda function?

Type hint function accepting a Union

type hint for input parameter which will be modified

Adding default parameter value with type hint in Python

Override type-hint of a parameter in __init__

PHPDoc or type hint class as parameter to method

How to pass type as a function parameter