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?
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 .
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.
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] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With