Search code examples
pythontype-hintingpyright

Is there a way to mark variables as constant / unchangeable in pyright?


I tried googling but I haven't come across a way to use a type annotation to mark a variable as constant in pyright. I think the type Constant is more like scalar constant rather than the C/C++ keyword const.

Any thoughts appreciated.

Thanks.


Solution

  • Since Python 3.8, you can type-hint a variable as Final(API docs, PEP591), to determine that it should not be changed beyond this point.

    # type1.py
    from typing import Final
    foo: Final = 1
    foo = 2 # raises an error
    
    $ mypy type1.py --pretty
    type1.py:3: error: Cannot assign to final name "foo"  [misc]
        foo = 2
        ^~~~~~~
    Found 1 error in 1 file (checked 1 source file)
    

    You can also add more type information by enclosing the type in square brackets: bar: Final[float] = 2