简体   繁体   中英

Python type hinting with numbers

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM