From 0d1e2b568864df422f42fc7f20d1b15a7688ecfa Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Fri, 29 Sep 2023 09:32:58 +0100 Subject: [PATCH] python: further notes on type hinting --- .../Python/Concepts/Type_hinting.md | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/Programming_Languages/Python/Concepts/Type_hinting.md b/Programming_Languages/Python/Concepts/Type_hinting.md index 599873f..047e6b3 100644 --- a/Programming_Languages/Python/Concepts/Type_hinting.md +++ b/Programming_Languages/Python/Concepts/Type_hinting.md @@ -24,15 +24,32 @@ def greet(name: str) -> str: return "Hello, " + name ``` -### Complex data types - -// TODO: Give examples of lists, tuples, dictionaries, sets - ### Classes // TODO: Add examples -### Optional types +## Complex data types + +// TODO: Give examples of lists, tuples, dictionaries, sets + +## Custom dictionay types + +We can create custom dictionay types in the manner of TypeScript types and interfaces as follows: + +```py +class ArticleInfo(TypedDict): + timestamp: str + article_title: str + link: str +``` + +We could then use it thus: + +```py +def parse_articles() -> List[ArticleInfo]: +``` + +## Optional types `Optional` can be used to indicate that a variable can be `None` or the specified type. @@ -48,7 +65,7 @@ def find_index(numbers: List[int], target: int) -> Optional[int]: The function above returns an `int` or `None`. -### Union types +## Union types `Union` can be used to indicate that a variable can be one of several types.