Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typing module in Python 2.7

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?

like image 588
code base 5000 Avatar asked Jan 27 '17 12:01

code base 5000


People also ask

Does Python 2 support type hints?

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar , and Generic .

Is typing in Python standard library?

Project description. This is a backport of the standard library typing module to Python versions older than 3.5. (See note below for newer versions.) Typing defines a standard notation for Python function and variable type annotations.

Does Python 3.8 support typing?

The typing module adds support for type hints. It contains some of the types you will use most often: List, Dict, and Tuple. Similarly, you can annotate that a dictionary maps strings to integers by Dict[str, int] .


1 Answers

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.

like image 101
Serge Ballesta Avatar answered Sep 21 '22 08:09

Serge Ballesta