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.
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.
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.
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.
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.
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