Inference question: empty list and .append() call #8066
-
Code sample in pyright playground # pyright: strict
def hello_world(x: int) -> list[str]:
result = []
if x % 2 == 0:
result.append("hello")
return result
# Type of "append" is partially unknown
# Type of "append" is "(object: Unknown, /) -> None" (reportUnknownMemberType)
# Return type, "list[Unknown]", is partially unknown (reportUnknownVariableType) Hi! In the code snippet above, as a human reader, I can tell that When I try the same thing in the mypy playground and add a couple of As a new Pyright user, I've gotten the impression that Pyright's inference is in general stronger / more aggressive (please correct me if I'm mischaracterizing it) than mypy's, and so I would have expected that Pyright would infer that Sorry for the long-winded question. The short version is: why does Pyright say that |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Pyright's type inference philosophy is based on the principle that the type of an object is established at the time it is constructed. You can't, for example, say that a list object starts its life as a The same principle applies here. At the time the list is constructed, its type is |
Beta Was this translation helpful? Give feedback.
Pyright's type inference philosophy is based on the principle that the type of an object is established at the time it is constructed. You can't, for example, say that a list object starts its life as a
list[str]
and later change your mind and decide that you want it to be alist[str | int]
. All subsequent operations are validated based on the type of an object that it had when it was created. The methods that can be safely called on that object are based on its type. Its type is not influenced by the methods that are called on it; that would be backward.The same principle applies here. At the time the list is constructed, its type is
list[Unknown]
because there is no additional context …