4

For example, we can indicate a variable is of a certain type:

a: float = 5.

Can we also indicate that a function is of a certain type?

import typing

FunctionType = typing.Callable[[float],float]

def a(v: float)->float:
    return v

How do we specify that we intend 'a' to be of type 'FunctionType'?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Vince
  • 3,979
  • 10
  • 41
  • 69
  • 1
    Given your code, `a` *is* of type `FunctionType`. You don’t need to do anything else. – Konrad Rudolph May 10 '22 at 10:12
  • @KonradRudolph in the same way that there is no need for 'a' to be indicated of type 'float' (first example), there is no need to indicate 'a' should be of type 'FunctionType' (second example). But specifying the type allows for code clarity and for linters to catch possible errors. – Vince May 10 '22 at 10:58
  • 1
    This somewhat makes sense if you're trying to write a callback which conforms to an interface. However, *this* isn't the place where that interface should be enforced or checked. That interface would be checked later in some caller which accepts this callback, e.g. `def f(cb: FunctionType): ...`. Now, if you try to do `f(a)`, this is the place where the type checker would complain about type incompatibility. But double enforcing that a function which already declares its signature conforms to some type declaration is somewhat inconsequential, as that's not where `f` and `a` ultimately meet. – deceze May 10 '22 at 11:26
  • @Vince That’s not what I mean. You already *did* explicitly specify the type of `a` by annotating its parameters and return type in its definition. That’s as explicit as it gets (and more than that wouldn’t be desirable). `typing.Callable` is a special form that’s used *only* for verifying that a declared function conforms to this type (when assigning a function to another name, e.g. when passing it as a parameter). It isn’t intended to be used when defining a function. – Konrad Rudolph May 10 '22 at 11:26
  • I think what Vince is trying to ask is how to use *named* types for functions. They defined a type `FunctionType`, and would like `a` to be of type `FunctionType`. If later, they decide to also accept `int` as input, it should be as simple as changing the one line defining `FunctionType` instead of all function signatures (assuming the implementation do not change if an integer is passed to the function). – leleogere May 10 '22 at 11:39

0 Answers0