Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use Python 3.9 type hinting in its previous versions?

In Python 3.9 we can use type hinting in a lowercase built-in fashion (without having to import type signatures from the typing module) as described here:

def greet_all(names: list[str]) -> None:
    for name in names:
        print("Hello", name)

I like very much this idea and I would like to know if it is possible to use this way of type hinting but in previous versions of python, such as Python 3.7, where we have write type hinting like this:

from typing import List

def greet_all(names: List[str]) -> None:
    for name in names:
        print("Hello", name)
like image 570
kbnt Avatar asked Sep 17 '20 13:09

kbnt


1 Answers

Simply, import annotations from __future__ and you should be good to go.

from __future__ import annotations

import sys
!$sys.executable -V #this is valid in iPython/Jupyter Notebook


def greet_all(names: list[str]) -> None:
    for name in names:
        print("Hello", name)
        
        
greet_all(['Adam','Eve'])

Python 3.7.6
Hello Adam
Hello Eve
like image 178
alec_djinn Avatar answered Sep 26 '22 12:09

alec_djinn