Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 77 ยท Python Interview Questions

Python: Walrus, match, Exception Groups, Pickling and Typing

Answer modern Python interview questions on the walrus operator, structural pattern matching, exception groups, pickling and its risks, and type hints with generics.

Python interviews used to stop at lists, dicts and decorators. Now they also check whether you know the language since version 3.8: the walrus operator, match statements, exception groups, and the typing system that makes large code bases manageable. Each topic comes with a favorite trap, such as "is match just a switch?" or "why is unpickling untrusted data dangerous?".

Every example runs in the page on Python 3.14 (Pyodide). The older fundamentals are in Python: Mutability, Identity and the Data Model, Python: OOP, MRO and the GIL and Python: Iterators, Generators and Comprehensions. For the language reference see the Python tutorial.

Modern Python in four ideas

Walrus Assign inside an expression.
match Match the shape of data.
Exception groups Handle several errors at once.
Type hints Documentation that tools can check.

Pickling is the odd one out. It is old, and it is a security risk.

1 / 2

What is the walrus operator?

Short answer: := is an assignment expression (Python 3.8). It assigns a value to a name and returns that value, so you can use the result in the same expression. The name comes from the way := looks like a walrus lying on its side.

It removes a repeated call or an awkward loop. Typical uses: reading chunks until empty, filtering with an expensive function you also want to keep, and testing a regular-expression match once. Rules and traps: it needs parentheses in many places (print((n := 5))), it cannot be used as a bare statement (x := 5 alone is a SyntaxError), and inside a comprehension the name leaks to the enclosing scope, unlike the loop variable. Do not overuse it: if it makes a line harder to read, use two lines.

Python Walrus: compute once, test, and keep the value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How does match work? Is it a switch statement?

Short answer: match (Python 3.10) is structural pattern matching. It is more powerful than a C-style switch: each case is a pattern that checks the shape of the subject (its type, length, keys) and can bind names to its parts at the same time.

Pattern kinds to know:

  • Literal: case 404:, case "quit":; | combines alternatives (case 401 | 403:).
  • Capture: a bare name such as case x: matches anything and binds it. A bare name is always a capture, never a comparison to an existing variable. To compare with a constant, use a dotted name (case Color.RED:) or a literal.
  • Wildcard: case _: matches anything and binds nothing (the default).
  • Sequence: case [x, y]:, case [first, *rest]:. Strings are not treated as sequences.
  • Mapping: case {"type": "click", "x": x}: matches dicts that have at least those keys.
  • Class: case Point(x=0, y=y): checks the type and attributes (for dataclasses, positional patterns work via __match_args__).
  • Guard: case [x, y] if x == y: adds a condition.

Cases are tried top to bottom and the first match wins, so put specific patterns before general ones.

Python match: shapes, guards and classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last block is the question interviewers love: case RED: matches anything and rebinds RED. Python even refuses a bare capture that makes later cases unreachable (SyntaxError), which is how you notice it in practice.

What are exception groups and except*?

Short answer: Python 3.11 added ExceptionGroup for "several unrelated errors at the same time", which concurrent code produces: asyncio.TaskGroup runs tasks together, and if two fail you want both errors, not only the first. An ExceptionGroup(message, [exc1, exc2, ...]) wraps them. You handle it with except*, which matches the sub-exceptions by type, handles the matching ones, and re-raises the rest as a new group.

Differences from except: several except* clauses can run for one group (each takes its matching members), you cannot mix except and except* in one try, and inside except* the name is always a group, even for a single error. BaseExceptionGroup exists for KeyboardInterrupt-style errors.

Python except* handles the matching members, re-raises the rest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What is pickling, and why is pickle.loads dangerous?

Short answer: Pickling serializes (turns into bytes) almost any Python object so you can save it or send it to another process; unpickling rebuilds it. multiprocessing uses it to move arguments and results between processes. It handles most built-ins, your own classes, and shared references (an object referenced twice is rebuilt once, and cycles work).

Things it cannot or should not do: lambdas, open files, sockets and locks are not picklable, and the pickle format is specific to Python and can change between versions (so it is a poor long-term storage format; JSON, Protocol Buffers or Parquet are better).

The security answer is the one to remember: unpickling can run arbitrary code. The format can tell the unpickler to call any importable callable (through __reduce__), so loading a pickle from an untrusted source (a download, a cache a user can write to, a network socket) is remote code execution. Never unpickle untrusted data; use JSON for data you receive. If you must, sign the data with an HMAC, or restrict allowed classes with a custom Unpickler.find_class.

Python pickle: round trip, shared references and the __reduce__ danger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How do type hints work, and what do generics and Protocol add?

Short answer: type hints are annotations. Python does not enforce them at runtime; tools such as mypy, pyright and your editor check them before you run the code, and libraries such as Pydantic and FastAPI read them at runtime. A hint on def f(x: int) -> str costs nothing and lets f("a") run (and fail somewhere else) unless a checker catches it.

The vocabulary worth knowing:

  • Built-in generics: list[int], dict[str, int], tuple[int, ...]; union with | (int | None, 3.10+, instead of Optional[int]).
  • Any (turns checking off), object, Callable[[int], str], Literal["r", "w"], Final, TypedDict for dict shapes, NamedTuple and dataclasses for records.
  • Generics: a function that works for any element type but ties input to output: def first[T](items: list[T]) -> T (the 3.12 syntax; older code uses TypeVar("T")). type Row = dict[str, int] (3.12) declares an alias.
  • Protocol: structural typing (static duck typing). A class satisfies a Protocol just by having the right methods, with no inheritance. Add @runtime_checkable to allow isinstance against it, which checks only that the methods exist.
  • Self, override (3.12), and annotations that are evaluated lazily from Python 3.14 (so forward references work without quotes).

The interview-level answer to "why use types if Python ignores them?" is: they catch mistakes early, make refactoring safe, document intent, and speed up editors, at no runtime cost. Use them first on public interfaces.

Python Hints are not enforced; Protocol is structural; generics link types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the effect of if (n := len(items)) > 10:?

    The walrus operator assigns and returns the value, so n is available afterwards and the length is computed only once.
  2. 2. In match status: case ERROR_CODE:, where ERROR_CODE is a module-level variable, what happens?

    A bare name in a pattern is a capture pattern. To compare with a constant use a dotted name (Codes.ERROR) or a literal.
  3. 3. When a TaskGroup has two failing tasks, how can you handle a ValueError from one of them and let the rest propagate?

    The failures arrive as an ExceptionGroup. except* extracts the matching members and re-raises the unmatched ones.
  4. 4. Why should you never call pickle.loads on data from an untrusted source?

    Unpickling follows instructions inside the data, including calling importable callables through reduce. Use JSON for untrusted input.
  5. 5. What does Python do at runtime with the annotation in def f(x: int) when you call f('a')?

    Annotations are metadata. Static checkers such as mypy and pyright (or runtime libraries like Pydantic) are what act on them.

Summary

  • := assigns inside an expression; use it to avoid repeated calls, mind the scope leak from comprehensions, and do not overuse it.
  • match is structural pattern matching: it checks shapes (sequences, mappings, classes), binds names, supports guards, and treats a bare name as a capture.
  • ExceptionGroup and except* handle several simultaneous errors, such as those from asyncio.TaskGroup; unmatched members are re-raised.
  • Pickle serializes Python objects, keeps shared references and cannot handle lambdas or sockets; unpickling untrusted data can run arbitrary code.
  • Type hints are not enforced at runtime; they feed checkers and tools. Generics link types, Protocol is structural, and X | None replaces Optional[X].

Next: Python: Classic Coding Questions.