ty: Error emitted because object is inferred as having `Element[Literal["testsuites"]]` when `Element[str]` was expected
Summary
Thank you so much for ty, it’s already much better than the alternatives in both speed and ease of setup.
The error I’m seeing suggests that ty currently does not resolve Literal values into their actual types.
E.g., ty fails this code
import xml.etree.ElementTree as ET
testsuites = ET.Element("testsuites")
testsuite = ET.SubElement(testsuites, "testsuite")
# ^^^^^^^^^^ Expected `Element[str]`, found `Element[Literal["testsuites"]]`
Full output:
❯❯❯ ty check ty_error.py
error: lint:invalid-argument-type: Argument to this function is incorrect
--> ty_error.py:4:27
|
3 | testsuites = ET.Element("testsuites")
4 | testsuite = ET.SubElement(testsuites, "testsuite")
| ^^^^^^^^^^ Expected `Element[str]`, found `Element[Literal["testsuites"]]`
5 | # ^^^^^^^^^^ Expected `Element[str]`, found `Element[Literal["testsuites"]]`
|
info: Function defined here
--> stdlib/xml/etree/ElementTree.pyi:140:5
|
138 | def __bool__(self) -> bool: ...
139 |
140 | def SubElement(parent: Element, tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ...
| ^^^^^^^^^^ --------------- Parameter declared here
141 | def Comment(text: str | None = None) -> _CallableElement: ...
142 | def ProcessingInstruction(target: str, text: str | None = None) -> _CallableElement: ...
|
info: `lint:invalid-argument-type` is enabled by default
Found 1 diagnostic
Expected behavior: ty should not fail this code.
Tested it with both ty-0.0.0a7 and ty-0.0.0a8 (commit 994caa6fcc2fdc7ab5e56dd1b86e3075aa404b9a)
Version
No response
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 15 (9 by maintainers)
@mikeshardmind We definitely agree that inferring a literal type for a class specialization isn’t right. Your
ContextVarexample is another instance of exactly what we’re trying to resolve with this discussion. We just merged https://github.com/astral-sh/ruff/pull/18102, which implements the stopgap option I described upthread; with that merged theinvalid-argument-typediagnostic goes away. [playground]These assignment examples are a separate discussion. This example, as written, is allowed by ty, and highlights what is possibly more of a bug in how our playground renders things. We track declared types and inferred types separately. The type hints that are shown in the playground:
are showing the inferred types for those expressions, not their declared types. There are no annotations, and so we’re using
Unknownas the implicit declared type forx, and so both assignments are accepted.For the inferred type we purposefully infer the more precise literal value type. That’s what shown in the inlay type hint. It’s also what’s used when passing
xin as an argument in a call, as seen in e.g.reveal_typediagnostics [playground]:I say that you could consider this a rendering bug in the playground, because if you “accept” the first inlay hint, putting it into the code as an actual annotation:
then the second assignment does fail as you say [playground], since
Trueis not assignable to the (now explicit) declared type ofx. So it’s arguably confusing that you have to notice the subtly different coloring of the inlay hint (which isn’t actually in the source file) vs the declared type annotation (which is), and that there is different behavior for the two.Adding another wrinkle, if you accept both inlay hints:
then both assignments are accepted again, since ty allows redefinitions of a symbol at a new type if you explicitly annotate the later definition. [playground]
Is
Nonea “value-based refinement” type?I’ve seen this now with
Literal[False]being inferred and erroring, where aboolinference would work.I think the general principle here should be not to infer value refinements (Literals in python’s type system) for non-final variables, as the value based refinement would preclude changing the value anyway.
I mentioned in https://github.com/astral-sh/ruff/pull/18102 but not here that the literal promotion also does not happen when you explicitly specialize a generic class:
If you squint this framing applies to the generic-function-returns-generic-class example, too — you’ve explicitly specialized the class in the return type annotation, and so my proposed literal promotion doesn’t apply.
I don’t know that I’d call it an error — at least not in the sense of a diagnostic being produced. The revealed type for this example in https://github.com/astral-sh/ruff/pull/18102 is specialized with a literal, though:
You might expect to get an
invalid-return-typediagnostic, but that could only come from in the function body, and the literal type doesn’t propagate from the call site into the function body.Are you thinking that this might be an unsoundness?
There’s also an option in between these two, which you could consider a hacky approximation of bidirectional type checking: infer the literal type when inferring a specialization of a function, and infer the instance type when inferring a specialization of a class. The rationale being that a class specialization is more likely to be “persistent” or “long-lived”, and therefore more likely that the widened instance type is what is intended. But that a function specialization is only (and can only be) used for a specific call site, and therefore more useful to propagate the more specific literal type into the return type.
(And to clarify, this would be a stopgap, not a long-term solution to this issue.)
I think this is also possibly a typeshed issue.
SubElementis declared as taking justElement, which isElement[str]because of a TypeVar default, but I suspect it doesn’t actually require a specific kind of Element.(Side note: I feel we may have gone a bit overboard with TypeVar defaults. They can and do cause subtle usability issues. It’s also sort of annoying that
Elementis invariant in its TypeVar; it can’t be covariant because in theory somebody could be assigning to thetagfield.)Even if a typeshed fix helps in this specific case, you might run into similar issues elsewhere too. The
Unknown |solution feels a bit dangerous because you’re injecting (essentially) Any into what looks like fully typed code. Upcasting Literals in inferring generics feels a little unprincipled but might work well in practice.Thank you for a quick reply! I think all these solutions sounds reasonable. It might be easier to switch from pytype to ty if they follow similar logic, but there are probably some issues with pytype’s approach that I don’t know about (and it’s very slow).
I think I don’t fully understand the advantage of the first approach, because we explicitly provide a
"string literal"and I don’t even know how to make it not literal. So, assuming that it’s a union ofUnknown|Literalis a bit dangerous, because the type is is fact known. Especially from the standpoint of the developer – all code is very explicit with datatypes here.Anyways, thanks for reacting. Just wanted to provide another potential test-case.
Although
Literal["testsuites"]is assignable tostr, ty is correct in thinking thatElement[Literal["testsuites"]]is not assignable toElement[str]That’s becauseElementis generic over an invariant TypeVar in typeshed’s stubs (and typeshed’s stubs are what ty uses as the sole source of truth for types in the standard library):https://github.com/python/typeshed/blob/41b2f9e7b4f0494b26052552d590886ed524b4aa/stdlib/xml/etree/ElementTree.pyi#L86-L89
So the issue here is the fact that we infer the
testsuitesvariable as being of typeElement[Literal["testsuites"]]at all – we need to avoid that, and instead infer it as some type that is assignable toElement[str]. There are several ways in which we could accomplish this:testsuites, we could infer the type of the variable as beingElement[Unknown | Literal["testsuites"]], which would be assignable toElement[str].Literaltypes when inferring specialisations (I believe that is what both mypy and pyright are doing here); this would mean that we would inferElement[str]for the variableElement[str]is required in order for thetestsuite = ET.SubElement(testsuites, "testsuite")call to succeed without any typing errors, and use that information as part of our decision-making process when deciding what type to infer for thetestsuitesvariable.All of these options have their tradeoffs in terms of the user experience and their implementation complexities. It’s a general issue that we’re aware of and that we’re still debating how to fix.