0

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

2
  • 3
    As you said, it's just a type hint. It tells the user that it expects to get an integer, but no enforcement action will be taken. Commented Jan 7, 2023 at 12:49
  • As @MechanicPig rightly said no implicit casting goes on when you used type hint. So you will have to do your casting explicitly. return int(n) * 10 Commented Jan 7, 2023 at 12:59

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.