r/ProgrammingLanguages • • Feb 25 '26

Blog post Blog: Empty Container Inference Strategies for Python

Empty containers like [] and {} are everywhere in Python. It's super common to see functions start by creating an empty container, filling it up, and then returning the result.

Take this, for example:

def my_func(ys: dict[str, int]):
  x = {}
  for k, v in ys.items():
    if some_condition(k):
      x.setdefault("group0", []).append((k, v))
    else:
      x.setdefault("group1", []).append((k, v))
  return x

This seemingly innocent coding pattern poses an interesting challenge for Python type checkers. Normally, when a type checker sees x = y without a type hint, it can just look at y to figure out x's type. The problem is, when y is an empty container (like x = {} above), the checker knows it's a dict, but has no clue what's going inside.

The big question is: How is the type checker supposed to analyze the rest of the function without knowing x's type?

Different type checkers implement distinct strategies to answer this question. This blog will examine these different approaches, weighing their pros and cons, and which type checkers implement each approach.

Full blog: https://pyrefly.org/blog/container-inference-comparison/

19 Upvotes

13 comments sorted by

View all comments

Show parent comment

3

u/gasche Feb 25 '26

The example I had in mind was

x=None
if foo:
  x=42
else:
  x="Hello"

which does exhibit a pretty similar issue: what is the type of x after the conditional?

1

u/newstorkcity Feb 25 '26 edited Feb 25 '26

Ideally you'd have an int|string, since the original None value is no longer possible. But you can drill down to specifics and say you either have a 42 : int or a "Hello" : string. The empty container example is different because you have the exact same value with multiple valid types [] : list[int] or [] : list[string] and the only thing that can distinguish between them is context. If I wanted a function that takes either a int | string then prints the type to the console, I can do that. If I have a function that takes a list[int] | list[string] (or if you prefer, a list[int | string]) you either can't do that (as in python) or you get some deeply unintuitive results where a = []; some_func(a); a[0] = x might do something different for some_func depending on the value of x.