value = 10 #pyright: const
...
value = 3 #error here
Or something similar and Pyright will emit an error if the value is changed across the program
Maybe even a variable that can be assigned only once would be interesting like:
value = otherfunction() #pyright: once
...
value = 3 #error here
As far as I'm aware, there's currently no standard way in the Python spec to annotate variables as constant.
I'll think about this more, but I'm not in favor of introducing pyright-specific syntax, even if it's in comments.
The only thing I can think that can add this without a comment is a config option like:
python.uppercase_variables_are_constants = True
I like that idea! It's consistent with the PEP 8 naming conventions, and most Python code already follows that convention.
What about https://mypy.readthedocs.io/en/latest/final_attrs.html from typing_extensions?
Or does this checker aim not to use typing_extensions?
@silviogutierrez Didn't know about Final, it seems experimental
mypy examples shows:
DEFAULT_ID: Final = 0
BORDER_WIDTH: Final = 2.5
# etc...
Isn't this too repetitive?
Uppercase variables should always be constants according to PEP8 anyway!
Their only good point is:
A final attribute declared in a class body without an initializer must be initialized in the __init__ method (you can skip the initializer in stub files):
class ImmutablePoint:
x: Final[int]
y: Final[int] # Error: final attribute without an initializer
def __init__(self) -> None:
self.x = 1 # Good
It's somewhat like references as class fields in C++, not bad
This is the only good reason why I would support Final in Pyright
I think it makes sense to implement support for Final, but I still like @Yatima1460's suggestion for treating upper-case names as constants. The latter would need to be optional (off by default).
This is now implemented in version 1.0.27, which I just published.
Most helpful comment
I like that idea! It's consistent with the PEP 8 naming conventions, and most Python code already follows that convention.