Pyright: typing.Final should be error when used class attribute updating except __init__ method

Created on 8 Jun 2020  Â·  6Comments  Â·  Source: microsoft/pyright

Describe the bug

According to PEP 591, typing.Final can use to class attribute updating only in __init__ method but Pyright not report error when used it in other places.

A final attribute declared in a class body without an initializer must be initialized in the __init__ method (except in stub files):
https://www.python.org/dev/peps/pep-0591/#semantics-and-examples

Expected behavior
Error message should be displayed when set class attribute except in __init__ method (including when skipped initialization).

Screenshots or Code

from typing import Final


class Cat:

    name: Final[str] = 'bella'  # This line should report error msg (skipped initialization).

    def __init__(self) -> None:
        pass

    def set_age(self, age) -> None:
        self.age: Final[int] = 10  # This line should also report error msg because the method is not `__init__`.

image

VS Code extension or command-line

I'm using VS Code extension.

  • Pyright version: 1.1.41
  • VS Code version: 1.45.1
  • OS: Windows 10

p.s.

If Pyright will not be supported PEP 591, please close this issue (because of PEP 591 not listed on README).

addressed in next version bug

All 6 comments

By my reading of PEP 591, the first of the two cases in your example should not generate an error message.

class Cat:
    name: Final[str] = 'bella'

This is an acceptable usage of Final, as it defines a class variable. There are examples in the PEP documentation that mirror this usage.

The second case that you flagged should generate an error. This was an omission when I initially implemented support for PEP 591.

Thanks for the bug report — and for pointing out that I didn't mention PEP 591 in the documentation. Pyright does support both the final decorator and the Final annotation described in PEP 591.

This will be fixed in the next version of Pyright.

@erictraut
Thx for replying.

This is an acceptable usage of Final, as it defines a class variable. There are examples in the PEP documentation that mirror this usage.

Ah... that's right. I was misunderstood.

This will be fixed in the next version of Pyright.

Thanks for handling it!

This is now addressed in Pyright 1.1.42, which was just published.

Thanks for the update to fix it!

Thanks for writing the article on Pyright!

Was this page helpful?
0 / 5 - 0 ratings