Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does -> do in python

I saw a python example today and it used -> for example this was what I saw:

spam = None
bacon = 42
def monty_python(a:spam,b:bacon) -> "different:":
    pass

What is that code doing? I'm not quite sure I've never seen code like that I don't really get what

 a:spam,b:bacon  

is doing either, can someone explain this for me? I googled, "what does -> do in python" but no good searches came up that I found.

like image 845
ruler Avatar asked Oct 20 '13 16:10

ruler


People also ask

What is the meaning of -> in Python?

the -> int just tells that f() returns an integer (but it doesn't force the function to return an integer). It is called a return annotation, and can be accessed as f. __annotations__['return'] . Python also supports parameter annotations: def f(x: float) -> int: return int(x)

What does -> None do in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

What does Arrow do in Python?

Arrow is a flexible Python library designed to create, format, manipulate, and convert dates, time, and timestamps in a sensible and human-friendly manner. It provides an intelligent module API that allows dealing with dates and times with a few code lines and imports.

What does next () do in Python?

The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.


2 Answers

It is function annotation for a return type. annotations do nothing inside the code, they are there to help a user with code completion (in my experience).

Here is the PEP for it.

Let me demonstrate, what I mean by "annotations do nothing inside the code". Here is an example:

def fun(a: str, b: int) -> str:
    return 1

if __name__ == '__main__':
    print(fun(10, 10))

The above code will run without any errors. but as you can see the first parameter should be a string, and the second an int. But, this only is a problem in my IDE, the code runs just fine:

enter image description here

like image 167
Games Brainiac Avatar answered Oct 20 '22 21:10

Games Brainiac


They're function annotations. They don't really do anything by themselves, but they can be used for documentation or in combination with metaprogramming.

like image 22
Danica Avatar answered Oct 20 '22 22:10

Danica