iuuujkl
iuuujkl

Reputation: 2394

use same function for different types

I have following function:

def calculate_digits(number: Union[int, float, str]) -> int:
    absolute_value: float = abs(number)
    rounded_value: int = math.floor(absolute_value)
    total_digits_needed: int = calculate_length_integer(rounded_value)
    return total_digits_needed

As you can see, I want to use this for different python types : int, float, str... As the abs() only works for floats I was wondering, how do I deal best with this? Do I need to write a function with if, elsif statement to do this, or is there a better way to do this?

Upvotes: 0

Views: 101

Answers (2)

chepner
chepner

Reputation: 532093

First, abs doesn't just work for floats; it works for numbers. At the very least:

  • int
  • float
  • complex
  • decimal.Decimal

There may be others. You might even be able to use numbers.Number as the type hint, though I'm not sure if that might not be too broad.

Second, this function really should be two functions, as a string is quite different from a numeric type.

def calculate_digits(number: Union[int, float]) -> int:
    absolute_value = abs(number)
    rounded_value = math.floor(absolute_value)
    return cacalculate_length_integer(rounded_value)

def calculate_digits_from_string(n: str) -> int:
    x = ... # Convert the string to an appropriate number.
    # There isn't enough detail in the question to know
    # which strings can be appropriate converted; float(n)
    # might be sufficient, though it could fail for an arbitrary
    # string.
    return calculate_digts(x)

You could combine them again, but I wouldn't recommend it, as the work to convert a string to a number should be kept separate.

def calculate_digits(number: Union[int, float, str]) -> int:
    if isinstance(number, str):
        number = ...  # Convert as above
    absolute_value = abs(number)
    rounded_value = math.floor(absolute_value)
    return cacalculate_length_integer(rounded_value)

Upvotes: 1

Dur Topolanski
Dur Topolanski

Reputation: 29

For me abs() works on int too... I'm using python 3.9.

For example the code below works for me at least:

number = abs(3)

Check if you need to update

Upvotes: 1

Related Questions