Home > Software engineering >  Python type hinting with numbers
Python type hinting with numbers

Time:10-12

I've just come across a strange behaviour with Python's type hinting.

>>> def x(y: int):
    return y
>>> d=x('1')
>>> print(type(d))
<class 'str'>
>>> d
'1'

When I pass a number as string into the function where the argument is cast as int, it still produces string. I think a key to this unexpected behaviour is that it is not casting, but hinting. But why does it behave like this? If I pass 'one' as an argument it gives me a NameError.

CodePudding user response:

You're not casting anything inside the function and type hints are just that; hints. They act as documentation, they don't cast or coerce types into other types.

To do so you need

def x(y):
    return int(y)

And now to accurately type hint this function

def x(y: str) -> int:
    return int(y)

CodePudding user response:

Python's type-hinting is purely for static analysis: no type-checking at runtime is done at all. This will also work:

x("One")

Your One failed because One does not exist, but this will work:

One = "seventeen"
x(One)
  • Related