From 077460e62fe6c4ddbcf02a2a1215f6660359ee20 Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Sun, 15 Oct 2023 17:32:40 +0100 Subject: [PATCH] python: typehinting post3.10 syntax --- .../Python/Concepts/Type_hinting.md | 37 ++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/Programming_Languages/Python/Concepts/Type_hinting.md b/Programming_Languages/Python/Concepts/Type_hinting.md index 047e6b3..6876b5a 100644 --- a/Programming_Languages/Python/Concepts/Type_hinting.md +++ b/Programming_Languages/Python/Concepts/Type_hinting.md @@ -8,6 +8,8 @@ tags: [python, types] With type hinting we can add type information to variables, functions, and classes. This is not enforced by the Python interpreter but can be used by external tools like `mypy` to check the code. +Prior to 3.10, to use types you would have to import the types you wanted `from` the `typing` module. With later versions you can use them directly without importing from `typing`. + ## Basic syntax ### Variables @@ -30,11 +32,18 @@ def greet(name: str) -> str: ## Complex data types -// TODO: Give examples of lists, tuples, dictionaries, sets +We can type complex data types such as dictionaries, lists, tuples etc. -## Custom dictionay types +The following function takes a tuple comprising two integers as a parameter and returns a list of ints: -We can create custom dictionay types in the manner of TypeScript types and interfaces as follows: +```py +def populate_pair_values(pair: tuple[int, int]) -> list[int]: + return [i for i in range(pair[0], pair[1] + 1)] +``` + +## Custom dictionary types + +We can create custom dictionary types in the manner of TypeScript types and interfaces as follows: ```py class ArticleInfo(TypedDict): @@ -46,7 +55,7 @@ class ArticleInfo(TypedDict): We could then use it thus: ```py -def parse_articles() -> List[ArticleInfo]: +def parse_articles() -> list[ArticleInfo]: ``` ## Optional types @@ -56,7 +65,7 @@ def parse_articles() -> List[ArticleInfo]: ```py from typing import Optional -def find_index(numbers: List[int], target: int) -> Optional[int]: +def find_index(numbers: list[int], target: int) -> Optional[int]: try: return numbers.index(target) except ValueError: @@ -65,6 +74,16 @@ def find_index(numbers: List[int], target: int) -> Optional[int]: The function above returns an `int` or `None`. +Post 3.10, we don't need to use `Optional`, we can use a union to cover the `None` case. Refactoring the previous example: + +```py +def find_index(numbers: list[int], target: int) -> int | None: + try: + return numbers.index(target) + except ValueError: + return None +``` + ## Union types `Union` can be used to indicate that a variable can be one of several types. @@ -90,3 +109,11 @@ def my_function() -> List[int]: def my_function() -> List[Union[int, float]]: return [1, 2, 3] ``` + +Post 3.10 we can use `|` syntax instead of importing `Union`. E.g: + +```py + +def add(a: int | float, b: int | float) -> int | float: + return a + b +```