Python Type Checker Comparison: Empty Container Inference

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 list or 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 post will examine these different approaches, weighing their pros and cons, and which type checkers implement each approach. The information presented should be useful as you evaluate and select a type checker.

Strategy 1: Infer Any type for container elements pyrefly.org/blog/container-inference-comparison

The simplest approach is just to use Any type for the items in the container. E.g. if the developer writes x = [] then the type checker would infer the type of x to be list[Any]. This is what Pyre, Ty, and Pyright 1 mostly behave like at the time of writing.

Since the analysis does not require looking at any surrounding context at all, this approach is probably the easiest to understand and at the same time the most efficient for a type checker to implement.

Among the inference strategies we discuss today, inferring list[Any] produces the least amount of type errors: developers can insert anything into the list, and items read from the list will also be Any.

On the other hand, by inferring Any we are effectively giving up type safety. The type c…

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论