| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
|
typing.Final specifies that a value can't change, but it also specifies that the value can't be overridden in a subclass. class PropertyBase:
pass
class PropertyChild(PropertyBase):
pass
class Base:
x: ClassVar[PropertyBase] = PropertyBase()
class Child(Base):
x: ClassVar[PropertyChild] = PropertyChild() # error: Variable is mutable so its type is invariant...
It's good that pyright is reporting this error, because otherwise, when treating Child as Base, I could assign to its x a PropertyBase that is not PropertyChild, and invalidate the typing on Child. But the problem is that I don't know how to specify it as immutable. class PropertyBase:
pass
class PropertyChild(PropertyBase):
pass
class Base:
x: Final[PropertyBase] = PropertyBase()
class Child(Base):
x: Final[PropertyChild] = PropertyChild() # error: cannot be redeclared because parent class "Base" declares it as Final
How can I specify that the variable doesn't change, but it can be overridden in the subclass so that the tooling knows the more specific type? |
|
As you point out, Final implies both "immutable" and "can't be overridden". In your use case, you want to indicate that the field is read-only but still overridable by subclasses. There has been some discussion about adding ReadOnly to the type system, but it hasn't gone very far. This wasn't an issue prior to pyright enforcing invariance for mutable fields. Mypy users will also encounter the problem when this feature is implemented in mypy. You may need to resort to a # type: ignore to work around this current shortcoming in the type system. |
| Back | FazBrowse Home | New Git URL |
As you point out, Final implies both "immutable" and "can't be overridden". In your use case, you want to indicate that the field is read-only but still overridable by subclasses. There has been some discussion about adding ReadOnly to the type system, but it hasn't gone very far.
This wasn't an issue prior to pyright enforcing invariance for mutable fields. Mypy users will also encounter the problem when this feature is implemented in mypy.
You may need to resort to a # type: ignore to work around this current shortcoming in the type system.