-1

I'm interested in designing a high level function in Python, (I.E. a function that takes other functions as arguments) but I don't know of any good conventions for documenting such a function. For example let's say I have a function "low_level" that takes an int and returns an int.

def low_level(x):
    """
    x: int
    """
    return x + 5

And suppose I want to write a function "high_level" that takes a function like low_level as its input.

def high_level(f):
    return f(5)

How should I document high_level to make it clear what the arguements and output of the function "f" are? I had this idea of defining a "class" of functions that high_level can accept as arguments, but I've heard that function typing isn't possible in Python.

1 Answer 1

1

A good first step would be to use type hints:

#!/usr/bin/env python3

from typing import Callable, TypeVar


def low_level(x: int) -> int:
    return x + 5


T = TypeVar("T")


def high_level(f: Callable[[int], T]) -> T:
    return f(5)

This already tells you everything you need to know: high_level takes a Callable object as its argument, which in turn gets passed an int and returns "something", and that "something" is also the return type of high_level.

As for documentation, I would follow the style of the Python standard library, which contains many higher-order functions such as itertools.accumulate.

I am not very familiar with Python documentation generators, but I would assume that the documentation for high_level would be rendered something like this:

high_level<T>(f: int → T) → T

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.