Add a ...
initial value to attributes declared on object
's class
#13875
+4
−4
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Normally, attributes that are declared at class toplevel but are uninitialized there cannot be directly accessed from the class itself at runtime. For instance,
This makes sense because at runtime, the bare
x: int
"declaration" onFoo
toplevel is just an annotated assignment statement without a RHS, which semantically is a no-op. Nothing actually gets added to either the classFoo
or any of theFoo
object. But if we try to assign an initial value to the attribute,x
will be there:Pyrefly is making an attempt at reporting an error on this kind of issue, where if an attribute gets declared at class toplevel without an initial value, we ban all accesses to the attribute from the class object.
One issue we have, when enabling the error, is that many stub files on
typeshed
doesn't really pay much attention to the difference between initialized and uninitialized class toplevel attribute declarations. For example, there are several declarations inobject
class toplevel such as__doc__
and__dict__
where the value does actually exist on theobject
class directly, but typeshed models them as uninitialized class toplevel attribute which causes Pyrefly to misreport when those attributes are accessed.I don't know how far we could go with reporting this new kind of error (which neither mypy nor pyright would flag) eventually, but given that "fixing" the issue requires only trivial changes from the stub files, we may as well just try adding
= ...
to class-toplevel attributes that must exist at runtime, starting from the classobject
.2025-04-25 (@srittau): Deferred, pending further discussion with the wider typing community.