Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter with colon [duplicate]

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?

like image 481
ruedi Avatar asked Mar 02 '19 20:03

ruedi


People also ask

What does colon mean in python function arguments?

A colon is used to represent an indented block. It is also used to fetch data and index ranges or arrays. Another major use of the colon is slicing. In slicing, the programmer specifies the starting index and the ending index and separates them using a colon which is the general syntax of slicing.

Why is colon (:) used while defining a function?

Colons (:) introduce clauses or phrases that serve to describe, amplify, or restate what precedes them. Often they are used to introduce a quote or a list that satisfies the previous statement. For example, this summary could be written as "Colons can introduce many things: descriptors, quotes, lists, and more."

What are the 2 types of function parameters?

Parameter Types Presently, the type is one of ref, const, or val. The type indicates the relationship between the actual argument and the formal parameter. , for a full discussion of references.)


2 Answers

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

like image 151
chepner Avatar answered Sep 19 '22 09:09

chepner


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

like image 35
wbadart Avatar answered Sep 17 '22 09:09

wbadart