You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add Type Hints section to More Language Features lecture
Adds a compact section on Python type hints to the python_advanced_features
lecture, covering:
- Basic syntax (function parameters, return types, variable annotations)
- Common built-in types and container type syntax
- Demonstration that hints are not enforced at runtime
- Why type hints matter (readability, IDE support, error checking, LLM code)
- Connection to scientific Python and JIT compilation
Closes#343
Copy file name to clipboardExpand all lines: lectures/python_advanced_features.md
+101-1Lines changed: 101 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -29,7 +29,7 @@ It's here
29
29
1. as a reference, so we can link back to it when required, and
30
30
1. for those who have worked through a number of applications, and now want to learn more about the Python language
31
31
32
-
A variety of topics are treated in the lecture, including iterators, decorators and descriptors, and generators.
32
+
A variety of topics are treated in the lecture, including iterators, type hints, decorators and descriptors, and generators.
33
33
34
34
## Iterables and Iterators
35
35
@@ -459,6 +459,106 @@ Overall, `*args` and `**kargs` are used when *defining a function*; they enable
459
459
460
460
The difference is that functions with `*args` will be able to take *positional arguments* with an arbitrary size, while `**kargs` will allow functions to take arbitrarily many *keyword arguments*.
461
461
462
+
## Type Hints
463
+
464
+
```{index} single: Python; Type Hints
465
+
```
466
+
467
+
Python is a *dynamically typed* language, meaning you don't need to declare the types of variables.
468
+
469
+
(See our {doc}`earlier discussion <need_for_speed>` of dynamic versus static types.)
470
+
471
+
However, Python supports optional **type hints** (also called type annotations) that allow you to indicate the expected types of variables, function parameters, and return values.
472
+
473
+
Type hints were introduced in Python 3.5 and have become increasingly common in modern Python code.
474
+
475
+
```{note}
476
+
Type hints are **ignored by the Python interpreter at runtime** --- they do not affect how your code executes.
477
+
They are purely informational and serve as documentation for humans and tools.
478
+
```
479
+
480
+
### Basic Syntax
481
+
482
+
Type hints use the colon `:` to annotate variables and parameters, and the arrow `->` to annotate return types.
483
+
484
+
Here is a simple example:
485
+
486
+
```{code-cell} python3
487
+
def greet(name: str, times: int) -> str:
488
+
return (name + '! ') * times
489
+
490
+
greet('hello', 3)
491
+
```
492
+
493
+
In this function definition:
494
+
495
+
-`name: str` indicates `name` is expected to be a string
496
+
-`times: int` indicates `times` is expected to be an integer
497
+
-`-> str` indicates the function returns a string
498
+
499
+
You can also annotate variables directly:
500
+
501
+
```{code-cell} python3
502
+
x: int = 10
503
+
y: float = 3.14
504
+
name: str = 'Python'
505
+
```
506
+
507
+
### Common Types
508
+
509
+
The most frequently used type hints are the built-in types:
510
+
511
+
| Type | Example |
512
+
|-----------|----------------------------------|
513
+
|`int`|`x: int = 5`|
514
+
|`float`|`x: float = 3.14`|
515
+
|`str`|`x: str = 'hello'`|
516
+
|`bool`|`x: bool = True`|
517
+
|`list`|`x: list = [1, 2, 3]`|
518
+
|`dict`|`x: dict = {'a': 1}`|
519
+
520
+
For containers, you can specify the types of their elements:
An important point for new Python programmers: type hints are **not enforced** at runtime.
530
+
531
+
Python will not raise an error if you pass the "wrong" type:
532
+
533
+
```{code-cell} python3
534
+
def add(x: int, y: int) -> int:
535
+
return x + y
536
+
537
+
# Works fine, despite passing strings
538
+
add('foo', 'bar')
539
+
```
540
+
541
+
This is a key difference from statically typed languages like C or Java, where mismatched types cause compilation errors.
542
+
543
+
### Why Use Type Hints?
544
+
545
+
If Python ignores them, why bother?
546
+
547
+
1.**Readability**: Type hints make function signatures self-documenting. A reader immediately knows what types a function expects and returns.
548
+
2.**Editor support**: IDEs like VS Code use type hints to provide better autocompletion, error detection, and inline documentation.
549
+
3.**Error checking**: Tools like [mypy](https://mypy.readthedocs.io/) and [pyrefly](https://pyrefly.org/) analyze type hints to catch bugs *before* you run your code.
550
+
4.**LLM-generated code**: Large language models frequently produce code with type hints, so understanding the syntax helps you read and use their output.
551
+
552
+
### Type Hints in Scientific Python
553
+
554
+
Type hints connect to the {doc}`need for speed <need_for_speed>` discussion:
555
+
556
+
* High-performance libraries like [JAX](https://jax.readthedocs.io/) and [Numba](https://numba.pydata.org/) rely on knowing variable types to compile fast machine code.
557
+
* While these libraries infer types at runtime rather than reading Python type hints directly, the *concept* is the same --- explicit type information enables optimization.
558
+
* As the Python ecosystem evolves, the connection between type hints and performance tools is expected to grow.
559
+
560
+
For now, the main benefit of type hints in day-to-day Python is **clarity and tooling support**, which becomes increasingly valuable as programs grow in size.
0 commit comments