简体   繁体   中英

type hinting pitches a fit about function arguments but not the return type

I'm fairly new to Python and was happy to discover the type hinting feature in Python3. I read through PEP 484 and found this question on SO in which the person asking the question was wondering why the return type of a function wasn't being checked. The respondent pointed to a section in PEP 484 that stated checking doesn't happen at run time and that the intention is that the type-hint is to be parsed by an external program.

I fired up the python3 REPL and decided to try this out

>>> def greeting() -> str: return 1
>>> greeting()
1

So far so good. I got curious about function parameters so I tried this:

>>> def greeting2(name: str) -> str: return 'hi ' + name
>>> greeting2(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in greeting2
TypeError: Can't convert 'int' object to str implicitly

Now this is where the wheels seem to come off because it seems like, at least with respect to function parameters, there IS checking. My question is why is there checking for the parameters but not the return type?

Python doesn't use the type hints at runtime (not for the function parameters nor the return type). It's no different from:

>>> def greeting3(name): return 'hi ' + name
...
>>> greeting3(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in greeting3
TypeError: Can't convert 'int' object to str implicitly

You're getting that TypeError because you're trying to concatenate a string and an integer:

>>> 'hi ' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

As mentioned, the type hints aren't checked at runtime, they're intended for use during development by your editor / tools.

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