caimaoy
caimaoy

Reputation: 1228

How can I use Function Annotation in Python 2.7

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?

Upvotes: 3

Views: 5052

Answers (2)

bstpierre
bstpierre

Reputation: 31206

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
        ...

Upvotes: 4

Ned Batchelder
Ned Batchelder

Reputation: 375634

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.

Upvotes: 1

Related Questions