Skip to content

Automatically infer class variables based on declaration #4389

Closed

Description

There seems to be a limitation with Pylance detecting if a variable declared in a class is a class variable or not.

In particular, the following code:

from typing import ClassVar, Protocol

class SimpleProtocol(Protocol):
    a: ClassVar[str]

class SimpleClass:
    a = "test"

val: SimpleProtocol = SimpleClass()

Gives the following error:
image
As far as I understand, SimpleClass.a is in fact a class variable (and using it as such does not produce any runtime errors),

Changing SimpleClass definition to

class SimpleClass:
    a: ClassVar = "test"

gets rid of the error.

It would be nice if Pylance could automatically infer that a is a class variable without the need for explicit type annotations.

Tested with Pylance language server 2023.5.30 (pyright e1b6074b).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

fixed in next version (main)A fix has been implemented and will appear in an upcoming version

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions