3

I saw this source code in Ipython:

https://github.com/ipython/ipython/blob/e1e2e960315f0f98703f6b8b077b10c99d04d70a/IPython/core/completer.py#L314

I know it is a new feature called Function Annotation in python3.

but this code may also work in Python 2.7. Why?

How can I use Function Annotation in Python 2.7?

caimaoy
  • 1,148
  • 1
  • 11
  • 25
  • Even in PY3 the use of annotations is limited. The interpreter does not use them. https://www.python.org/dev/peps/pep-0484/ – hpaulj Feb 06 '17 at 04:47
  • http://stackoverflow.com/questions/35230635/type-hinting-in-python-2 – hpaulj Feb 06 '17 at 05:38

2 Answers2

4

You can't use the new (3.5+) annotation syntax directly in 2.7, but if you have python 3.4+ you can install mypy and run it on your 2.7 code with a different syntax. See PEP 484.

The example you pointed to in your link could be written in 2.7 as:

class Completion:
    def __init__(self, start, end, text, type=None, _origin=''):
        # type: (int, int, str, str, str) -> None
        ...
bstpierre
  • 30,042
  • 15
  • 70
  • 103
1

No, you can't use function annotations in Python 2.7. That said, the main use of function annotations is for gradual typing, which can be done with comments in Python 2.7.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662