带冒号的函数参数

我刚刚发现了这个函数:

def splitComma(line: str):
splits = Utils.COMMA_DELIMITER.split(line)
return "{}, {}".format(splits[1], splits[2])

我知道您可以通过类似于 a=39的参数来分隔参数,或者可以在参数中设置值,但是我没有看到类似于 line:str的冒号。我已经在线检查了函数定义,但是没有找到任何类似的东西。这个结肠是什么意思?

54932 次浏览

This is a type annotation used by static analysis tools to check, well, types. It helps ensure program correctness before you run the code.

It's a function annotation; function arguments and the return value can be tagged with arbitrary Python expressions. Python itself ignores the annotation (other than saving it), but third-party tools can make use of them.

In this case, it is intended as type hint: programs like mypy can analyze your code statically (that is, without running it, but only looking at the source code itself) to ensure that only str values are passed as arguments to splitComma.

A fuller annotation to also specify the return type of the function:

def splitComma(line: str) -> str:
...

(Note that originally, function annotations weren't assumed to have any specific semantics. This is still true, but the overwhelming assumption these days is that the annotations provide type hints.)