Advanced Typing -- Protocols, TypeVar, ParamSpec¶
advanced_typing ¶
Modern Python type-system demonstrations (3.12 - 3.14).
Each section below showcases one typing feature with full inline commentary. Together they cover the practical subset of Python's type system that appears in real codebases and interview discussions.
Sections¶
Protocol— structural subtyping (PEP 544)TypeVarwith default (PEP 696)ParamSpec+Concatenate— signature-preserving decorators (PEP 612)TypeGuard— user-defined type narrowing (PEP 647)@overload— multi-signature functions (typing.overload)- Generic
Stack[T]— PEP 695 syntax (class Foo[T])
References¶
- PEP 544 — https://peps.python.org/pep-0544/
- PEP 612 — https://peps.python.org/pep-0612/
- PEP 647 — https://peps.python.org/pep-0647/
- PEP 695 — https://peps.python.org/pep-0695/
- PEP 696 — https://peps.python.org/pep-0696/
- typing docs — https://docs.python.org/3.14/library/typing.html
Drawable ¶
Circle ¶
A simple shape — satisfies Drawable without inheriting it.
c = Circle(5.0) c.draw() 'Circle(radius=5.0)'
Source code in src/concepts/advanced_typing.py
Container ¶
A trivial single-value container, generic over T (PEP 695 syntax).
Demonstrates:
* PEP 695 class Foo[T] generics
* A .transform method that maps the contained value
c = Container(10) c.value 10 c.transform(lambda x: x * 2).value 20
Source code in src/concepts/advanced_typing.py
transform ¶
Apply func to the contained value, returning a new Container.
Container("hello").transform(len).value 5
Stack ¶
A LIFO stack, generic over element type T.
s = Stackint s.push(1) s.push(2) s.peek() 2 s.pop() 2 s.pop() 1 s.is_empty() True
Source code in src/concepts/advanced_typing.py
push ¶
pop ¶
Remove and return the top item.
Raises IndexError if the stack is empty.
Stackint.pop() Traceback (most recent call last): ... IndexError: pop from empty stack
Source code in src/concepts/advanced_typing.py
peek ¶
Return the top item without removing it.
Raises IndexError if the stack is empty.
Stackint.peek() Traceback (most recent call last): ... IndexError: peek at empty stack
Source code in src/concepts/advanced_typing.py
is_empty ¶
render ¶
Call .draw() on anything that satisfies the Drawable protocol.
render(Circle(3.0)) 'Circle(radius=3.0)'
add_logging ¶
Decorator that prepends a verbose boolean parameter.
When verbose=True, the function name and arguments are printed
before the call.
@add_logging ... def add(a: int, b: int) -> int: ... return a + b add(False, 1, 2) 3
Source code in src/concepts/advanced_typing.py
is_str_list ¶
Check whether val is a list consisting entirely of strings.
is_str_list(["a", "b", "c"]) True is_str_list(["a", 1]) False is_str_list([]) True
Source code in src/concepts/advanced_typing.py
process ¶
Return different types based on input type.
intinput -> doubled integerstrinput -> list of characters
process(5) 10 process("hi") ['h', 'i']