Skip to content

How do I annotate this function with abs() and division? #1211

Answered by Akuli
jwodder asked this question in Q&A
Discussion options

You must be logged in to vote

Sorry for the late reply. Looking at the docstring, the function is intended to be used only with floats and complex numbers, not with arbitrary types that happen to support absolute value and division (e.g. a 3D vector from some library). So you have two cases, either a float is passed in and the result is a float, or a complex is passed in and the result is a complex.

from __future__ import annotations  # for "|" syntax
from typing import overload

@overload
def signum(x: float) -> float: ...
@overload
def signum(x: complex) -> complex: ...

def signum(x: float | complex) -> float | complex:
    if x == 0:
        return 0
    else:
        return x / abs(x)

reveal_type(signum(5.2))  #…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by jwodder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants