Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static typing in python3: list vs List [duplicate]

What is the difference between using list and List when defining for example the argument of a function in python3? For example, what is the difference between

def do_something(vars: list):

and

def do_something(vars: List):

The documentation says:

class typing.List(list, MutableSequence[T])

Generic version of list. Useful for annotating return types.

but I'm not entirely sure what the above means.

I have similar questions for: dict vs Dict, set vs Set, etc.

like image 246
physics_researcher Avatar asked Oct 03 '18 14:10

physics_researcher


People also ask

Is static typing possible in Python?

Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.

Can you enforce typing in Python?

New in version 3.5. 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.

What is list from typing in Python?

List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.


1 Answers

Not all lists are the same from a typing perspective. The program

def f(some_list: list):
    return [i+2 for i in some_list]

f(['a', 'b', 'c'])

won't fail a static type checker, even though it won't run. By contrast, you can specify the contents of the list using the abstract types from typing

def f(some_list: List[int]) -> List[int]:
    return [i+2 for i in some_list]

f(['a', 'b', 'c'])

will fail, as it should.

like image 94
Patrick Haugh Avatar answered Nov 10 '22 18:11

Patrick Haugh