5

The typing module is a back port for earlier version of Python to infer input and output datatypes. I am having an issue getting it to work in Python 2.7.

import typing
def greeting(name): # type: (str) -> str
    """documentations"""
    return ('Hello ' + name)
print(greeting.__annotations__) # fails because doesn't exist.

I've also tried this:

import typing
def greeting(name # type: str
             ):
    # type: (...) -> str
    """documentations"""
    return ('Hello ' + name)

And this:

import typing

def greeting(name):
    # type: (str) -> str
    """documentations"""
    return ('Hello ' + name)

This should create an __annotations__ property on the class according to PEP484, but I do not see this happening at all.

What am I doing wrong with the backport code?

code base 5000
  • 3,812
  • 13
  • 44
  • 73
  • 1
    Possibly see http://stackoverflow.com/questions/35230635/type-hinting-in-python-2 – khelwood Jan 27 '17 at 12:31
  • @khelwood this does not work, so if I do what I did above with the type notation it doesn't work. The ```__annotations__``` never gets population in the 3.5 version or 2.7 – code base 5000 Jan 27 '17 at 12:37
  • Have you tried putting the type annotation comment on its own line? – zondo Jan 27 '17 at 12:45
  • @zondo i added additional information above. – code base 5000 Jan 27 '17 at 12:57
  • 2
    Are you running your code with something like `mypy --py2 program.py`? If you're running with normal Python, nothing is interpreting the type annotations. – zondo Jan 27 '17 at 12:58
  • @zondo ok, so you need to run mypy to use this, not the normal python.exe. Should this notation work with python 3.5 and 3.6? – code base 5000 Jan 27 '17 at 13:15
  • Where did this backport come from? How are we supposed to help you with code not in your question? What's "mypy"? – martineau Jan 27 '17 at 13:17
  • 1
    You would still need to run it with mypy. Python 3 introduces type annotations in normal syntax, but the comment stuff needs to be interpreted by mypy. – zondo Jan 27 '17 at 13:18
  • 1
    Note that there are other type annotation interpreters. You don't have to use mypy. – zondo Jan 27 '17 at 13:20

1 Answers1

6

typing is a module that was introduced in Python 3.5 . The examples in PEP 484 rely on a Python 3+, and __annotations__ is a Python 3 concept. The backport can only allow to use the types of functions defined in the typing module, but it does not change the Python engine to magically understand all Python 3 concepts.

A discussion in that other SO post suggests that the annotations should be accessible by using inspect.getsourcelines to research the first line right after the function declaration and starting with # type. A typed-ast module exists on pypi and should be able to parse Python 2.7 style annotations. Unfortunately it is only declared at beta level and only compatible with Python 3.

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252