Pyright: Constants type checking

Created on 18 Apr 2019  路  9Comments  路  Source: microsoft/pyright

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

addressed in next version enhancement request

Most helpful comment

I like that idea! It's consistent with the PEP 8 naming conventions, and most Python code already follows that convention.

All 9 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

giyyapan picture giyyapan  路  3Comments

tamuhey picture tamuhey  路  3Comments

tamuhey picture tamuhey  路  3Comments

benjaminsaljooghi picture benjaminsaljooghi  路  3Comments

Afsarsoft picture Afsarsoft  路  3Comments