Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hinting in Python 2

In PEP 484, type hinting was added to Python 3 with the inclusion of the typing module. Is there any way to do this in Python 2? All I can think of is having a decorator to add to methods to check types, but this would fail at runtime and not be caught earlier like the hinting would allow.

like image 643
Andrew Avatar asked Feb 05 '16 18:02

Andrew


People also ask

Does Python 2 support type hints?

According to PyCharm "PyCharm supports type hinting in function annotations and type comments using the typing module defined by PEP 484." The reference to TYPE COMMENTS makes it clear that it should be supported.

What is type hinting Python?

Introduction to Python type hints It means that you need to declare types of variables, parameters, and return values of a function upfront. The predefined types allow the compilers to check the code before compiling and running the program.

When was type hinting added to Python?

Type hints were first specified in PEP 484, like I mentioned in the previous video, and they were first introduced into Python in version 3.5. 00:33 So, let me show you what it kind of looks like by showing you an example of adding type information to a function.

What does type () do in Python?

Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.


1 Answers

According to Suggested syntax for Python 2.7 and straddling code in PEP 484 which defined type hinting, there is an alternative syntax for compatibility with Python 2.7. It is however not mandatory so I don't know how well supported it is, but quoting the PEP:

Some tools may want to support type annotations in code that must be compatible with Python 2.7. For this purpose this PEP has a suggested (but not mandatory) extension where function annotations are placed in a # type: comment. Such a comment must be placed immediately following the function header (before the docstring). An example: the following Python 3 code:

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:     """Embezzle funds from account using fake receipts."""     <code goes here> 

is equivalent to the following:

def embezzle(self, account, funds=1000000, *fake_receipts):     # type: (str, int, *str) -> None     """Embezzle funds from account using fake receipts."""     <code goes here> 

For mypy support, see Type checking Python 2 code.

like image 79
Mijamo Avatar answered Oct 09 '22 05:10

Mijamo