Type conversion during function call in python

Question:

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

Asked By: Nikhil

||

Answers:

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
Answered By: Ronin

This is happening because the map function applies the function f to each element of the list l, and then returns a map object that contains the results. The map object is an iterator that returns the results one by one when you iterate over it.

In this case, the map object will contain the results of calling f(11.2), f(2.2), f(3.3), and f(4.4), which are 112, 22, 33, and 44 respectively.

The reason that you are seeing the float values converted to int values is because the f function is defined to accept an int argument, and so when you pass a float value to it, it is automatically converted to an int before being passed to the function.

If you want to prevent the float values from being converted to int values, you can modify the f function to accept a float argument instead of an int argument. For example:
def f(n:float): return n*10 l = [11.2, 2.2, 3.3, 4.4] mfunc = map(f,l) print(list(mfunc)) this is output: [112.0, 22.0, 33.0, 44.0]

Answered By: Eagle123