Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/why use types from typing module for type hints [duplicate]

What is exactly the 'right' way for type hinting? My IDE (and resulting code) works fine for type hints using either of below options, but some types can be imported from the typing module. Is there a preference for using the import from the typing module over builtins (like list or dict)?

Examples:

from typing import Dict
def func_1(arg_one: Dict) -> Dict:
    pass

and

def func_2(arg_one: dict) -> dict:
    pass
like image 750
g_uint Avatar asked Mar 09 '26 07:03

g_uint


1 Answers

The "right" way is to use builtins when possible (e.g. dict over typing.Dict). typing.Dict is only needed if you use Python < 3.9. In older versions you couldn't use generic annotations like dict[str, Any] with builtins, you had to use Dict[str, Any]. See PEP 585

like image 177
Expurple Avatar answered Mar 10 '26 19:03

Expurple