Function parameter with colon

PythonFunction

Python Problem Overview


I just came across this function:

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

I am aware that you can separate parameters by , or can set a value within a parameter like a=39 but I have not seen a colon like line:str. I have checked the function definition online but could not find anything like this. What does this colon mean?

Python Solutions


Solution 1 - Python

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.)

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionruediView Question on Stackoverflow
Solution 1 - PythonchepnerView Answer on Stackoverflow
Solution 2 - PythonwbadartView Answer on Stackoverflow