pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

String literal generic parameter to `Type[]` not allowed

Open zsol opened this issue 7 months ago • 2 comments

Describe the Bug

from typing import *

SomeT = Type["Foo"]

class Foo:
    pass

Unfortunately from __future__ import annotations doesn't help here.

Sandbox Link

https://pyrefly.org/sandbox/?code=MQAg6gpgNgxg9gWwiALnVALZAFAngJwgDMpcQBlAQwDsATAIzgA8AaTASwGcQuRKQADpQDmEAFCgA7lkIhccAK4gYNEJPzsUENpwyVZNWiCgR91PowUpUuAe2rCe5vCgxxqAOgkSQACQgGBsqKAiYgRKYoCoTccEQc3JyGjEwAXD4AtCAA4hDWhJRQGSjsSDYCyDBYMADW9o4REAyUtZkgAKqcyIQAbqZQAPoothAAFACUqOj2nBUw1vYR+IRGwxWcbRBMFRpI1NaSmhiYyACSACIAouGR0RDcrpQHyJwKAgJw+NajEB7CHnwrHB4AhQnltCBhHBitDaMR7Jp2O42G4+vg2HkYOM2mANFo+HQQPgFM5cK53ME4SBaOxCPNSE45Ip8CB6Pg4JIuvgxGIiOyEOV6jxQZ9rAAqHnkRAQAAqIAAvCAZSMANoAIgAYnA4GqALo8mBQSicbhauDpECWwTGzhAA

(Only applicable for extension issues) IDE Information

No response

zsol avatar May 20 '25 10:05 zsol

Prefixing with the type keyword will work. I think this is because for possible implicit type aliases we initially treat this as a regular expression, which doesn't handle these string literals, and use the resulting type to decide if it's a regular assignment or an implicit type alias.

https://github.com/facebook/pyrefly/blob/main/pyrefly/lib/alt/solve.rs#L1943

One possible solution is to defer the error until after we decide it's an implicit type alias, in which case we can re-check it as an annotation.

yangdanny97 avatar May 29 '25 03:05 yangdanny97

The problem with rechecking it as an annotation is that many that require Usage bindings which we only generate for things we have a suspicion are types. This one will be tricky.

We eventually might have to persist scope info so we can figure out Usage later. But that's grim.

ndmitchell avatar May 29 '25 06:05 ndmitchell

Without this, we cannot have recursive types like this: JsonType = None | bool | int | float | str | list["JsonType"] | dict[str, "JsonType"]

spapanik avatar Sep 08 '25 21:09 spapanik