1
def f(ham: str, eggs: str = 'eggs') -> str:
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs

In the above block of code which got from https://docs.python.org/3.5/tutorial/controlflow.html#documentation-strings

My question is about the -> str in the above block of code. What does it do ?

new Q Open Wid
  • 2,225
  • 2
  • 18
  • 34
h4kr
  • 238
  • 1
  • 3
  • 13
  • 3
    But.. that link *explicitly explains* what it does. You have quite literally linked to the canonical documentation for that syntax. – Daniel Roseman Mar 28 '16 at 17:51
  • @DanielRoseman `def f(ham: str, eggs: str = 'eggs')` in this block they did mention **str**, so why did they again have to mark/say the same at the last? – h4kr Mar 28 '16 at 17:54
  • Because the `str` in that block has to do with the types of the variables getting passed in, not the one getting returned. – Bahrom Mar 28 '16 at 17:55
  • @DanielRoseman is right, your link also references [PEP 0484](https://www.python.org/dev/peps/pep-0484/#abstract) which goes into greater detail about this. – Bahrom Mar 28 '16 at 17:56
  • [PEP 0484](https://www.python.org/dev/peps/pep-0484/) is probably all you want to know about the current state of type hints / function annotations. – dawg Mar 28 '16 at 18:07

2 Answers2

7

It specifies the return value. It has nothing to do with the code at all and is just for documentation purposes.

Hans
  • 2,354
  • 3
  • 25
  • 35
4

Those are type hints. Various type checkers can use them to determine if you're using the correct types. In your example, you function is expecting ham of type str, and eggs of type str (defaulting to eggs). The final -> str implies that this function, should have a return type of str as well.

For more information see:

Community
  • 1
  • 1
Bahrom
  • 4,752
  • 32
  • 41
  • 1
    What if I do not return it as a string? – h4kr Mar 28 '16 at 17:57
  • 1
    Your code won't be affected - it would still run, but if you ran your code through a type checker, such as [mypy](http://mypy.readthedocs.org/en/latest/basics.html#type-checking-and-running-programs), you would get a warning. – Bahrom Mar 28 '16 at 18:01
  • 1
    `What if I do not return it as a string?` Try it and see. It depends on the context. Python will not type check the return if that is what you are asking. – dawg Mar 28 '16 at 18:01
  • And as @dawg mentioned - the best way to learn about these things is to try them out for yourself - bring up a shell, create a function that has that annotation (or copy it from the example) and try running it. – Bahrom Mar 28 '16 at 18:02