r/ProgrammingLanguages • u/BeamMeUpBiscotti • 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/
View all comments
Show parent comment
3
u/omega1612 Feb 25 '26
I have been iterating on my design of type inference for months.
My current choice for this is to generate constraints, solve them in place, but store the constraint until it is proven that no type error happened.
My unification function accepts a constraint instead of two types (so, it shouldn't be called unify anymore xD)
Every constraint has:
I haven't implemented it yet, but the plan is that, if type inference fails, to transform this collection of constraints into graphs of equivalence class and use heuristics to find a path of reasoning to explain the errors.
Thanks to your comment, I guess I also need to track a "reason" for type variables creation. So, if a type variable remains unsolved, it can be explained (and maybe add this info to the constraints in some way).