0

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.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
drwie
  • 115
  • 1
  • 2
  • 9
  • 3
    Python is not a compiled language, and the type hinting system is not used at runtime (unless you are using some specific third-party libraries). These typehints allow you to run static analysis tools such as mypy to determine if your code is respecting the contacts of functions/methods and respecting variable types when doing assignments. – flakes Oct 12 '21 at 13:50
  • Does this answer your question? [How to use type hints in python 3.6?](https://stackoverflow.com/questions/41356784/how-to-use-type-hints-in-python-3-6) – Alex Waygood Oct 12 '21 at 16:42

2 Answers2

5

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)
Alex
  • 509
  • 4
  • 8
1

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)
2e0byo
  • 5,305
  • 1
  • 6
  • 26