Nikhil
Nikhil

Reputation: 817

Type conversion during function call in python

In the example below I'm passing float value to a function accepting and int argument (using type hints). Looks like the value read into the function arg is a float nonetheless (was expecting int(11.2) * 10 = 110 instead of 112)

Why is this the case?

def f(n:int):
    return n*10
l = [11.2, 2.2, 3.3, 4.4]
mfunc = map(f,l)
print(list(mfunc))

Result: [112.0, 22.0, 33.0, 44.0]

** Process exited - Return Code: 0 ** Press Enter to exit terminal

Upvotes: 0

Views: 213

Answers (1)

Ronin
Ronin

Reputation: 2288

As @Mechanic Pig said n:int in function signature is just a hint for developer and its not converts to int.

So you cast to int

def foo(n: int):
  if type(n) is float:
      n = int(n)
  return n * 10

Or you can use assert to raise error if n is not int

def foo(n: int):
    assert type(n) == int, "must be int"
    return n * 10

or

def foo(n: int):
    if type(n) is not int:
        raise Exception(f"Must by int instead of {type(n).__name__}")
    return n * 10

Hints more useful when you use IDE that support it.

Here -> int: describes what type function returns

def foo(n: int) -> int:
    return n * 10

Upvotes: 2

Related Questions