0

Can anyone please tell me what is the difference between below two functions? They both look pretty similar except for ->.

foo1()

def foo1() -> None:
pass

foo2()

def foo2():
pass

When I call them the act in similar manner. So why use -> None ?. I know use of None of Python.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
  • `foo1` is using [type hints](https://docs.python.org/3/library/typing.html) – idjaw Sep 22 '16 at 01:04
  • See also: http://stackoverflow.com/questions/29770412/how-why-does-python-type-hinting-syntax-work – TerryA Sep 22 '16 at 01:06
  • 1
    @JimFasarakis-Hilliard First I tried searching by "-> in Python" in Google and in Stack Overflow. Nothing came up Try for yourself. I didn't knew the term type hinting. So what could have I done? – BlackBeard Sep 22 '16 at 01:45
  • 2
    @NiladriSekharBasu there's absolutely *nothing* wrong with it being marked as a duplicate.You get answers and the posts are linked. I understand why it was hard to find a sample, but don't take it negatively :-) – Dimitris Fasarakis Hilliard Sep 22 '16 at 01:46

1 Answers1

2

This is called type hinting, and is only used to help make it easier for the programmer to understand the return and input types of a program, as well as allow for external linting and static analysis programs to work on Python. Here is the official RFC explaining why it exists.

Type hints are not actually used by Python anyway (because Python is dynamically typed - the types are determined at runtime, not at compile time when the source is actually parsed) and can be safely omitted.

Functions conforming to your Version 2 are perfectly fine in every case.

Python 3 has inbuilt support for type hints with the typing module, while Python 2.7 requires the third-party mypy module.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
  • 1
    More precisely, the `typing` module is a part of the standard library in Python 3.5, but must be installed as a 3rd party library for Python 2.7 through 3.4. However, the _syntax_ for function annotations was added in Python 3.0 -- to use type annotations in Python 2.7, you need to use the comments in the form described in the PEP. Regardless of which version of Python you're using, you need to have a 3rd party type checker installed, whether that's mypy, pytype, Pycharm's builtin checker, etc... (As it turns out, there's a budding ecosystem of libraries and tools that understand type hints). – Michael0x2a Sep 22 '16 at 20:18