25

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.

Taylan Aydinli
  • 4,333
  • 15
  • 39
  • 33
ruler
  • 613
  • 1
  • 10
  • 17

2 Answers2

29

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

Community
  • 1
  • 1
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
7

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

Danica
  • 28,423
  • 6
  • 90
  • 122