|
316 | 316 | "odd('hi')" |
317 | 317 | ] |
318 | 318 | }, |
| 319 | + { |
| 320 | + "cell_type": "markdown", |
| 321 | + "metadata": {}, |
| 322 | + "source": [ |
| 323 | + "## annotating advanced types\n", |
| 324 | + "\n", |
| 325 | + "- only primitive types can be annotated directly\n", |
| 326 | + " - int, float, str, and bool\n", |
| 327 | + "- for advanced types, import capitalized type names from `typing` module\n", |
| 328 | + "- Union, Optional, Any, Tuple, List, Dict, Set, etc.\n", |
| 329 | + "- `List[int]` - list of integers\n", |
| 330 | + "- `Dict[str, int]` - dictionary with string keys and integer values\n", |
| 331 | + "- `Tuple[int, str, float]` - tuple with an integer, string, and float\n", |
| 332 | + "- `Set[bool]` - set of booleans\n", |
| 333 | + "- `Optional[str]` - optional string (can be None)\n", |
| 334 | + "- `Union[int, float]` - can be either an integer or a float\n", |
| 335 | + "- `Any` - any type\n", |
| 336 | + "- `Callable[[int, int], int]` - function that takes two integers and returns an integer\n", |
| 337 | + "- `Iterable[str]` - iterable of strings\n", |
| 338 | + "- `Iterator[int]` - iterator of integers\n", |
| 339 | + "- `a: int | float` - variable `a` can be either an integer or a float\n", |
| 340 | + "- `def foo(a: int | float) -> int | float:` - function `foo` takes an integer or a float and returns an integer or a float\n" |
| 341 | + ] |
| 342 | + }, |
| 343 | + { |
| 344 | + "cell_type": "code", |
| 345 | + "execution_count": 1, |
| 346 | + "metadata": {}, |
| 347 | + "outputs": [], |
| 348 | + "source": [ |
| 349 | + "from typing import List, Tuple\n", |
| 350 | + "\n", |
| 351 | + "def max_min(lst: List[float]) -> Tuple[float, float]:\n", |
| 352 | + " return max(lst), min(lst)" |
| 353 | + ] |
| 354 | + }, |
| 355 | + { |
| 356 | + "cell_type": "code", |
| 357 | + "execution_count": 2, |
| 358 | + "metadata": {}, |
| 359 | + "outputs": [], |
| 360 | + "source": [ |
| 361 | + "assert max_min([1.0, 2.0, 3.0, 4.0]) == (4.0, 1.0)" |
| 362 | + ] |
| 363 | + }, |
319 | 364 | { |
320 | 365 | "cell_type": "markdown", |
321 | 366 | "metadata": {}, |
|
869 | 914 | ], |
870 | 915 | "metadata": { |
871 | 916 | "kernelspec": { |
872 | | - "display_name": "oop", |
| 917 | + "display_name": "Python 3", |
873 | 918 | "language": "python", |
874 | 919 | "name": "python3" |
875 | 920 | }, |
|
883 | 928 | "name": "python", |
884 | 929 | "nbconvert_exporter": "python", |
885 | 930 | "pygments_lexer": "ipython3", |
886 | | - "version": "3.10.9" |
| 931 | + "version": "3.12.1" |
887 | 932 | } |
888 | 933 | }, |
889 | 934 | "nbformat": 4, |
|
0 commit comments