Skip to content

Commit

Permalink
Fixed bug that results in incorrect evaluation of class variables ass…
Browse files Browse the repository at this point in the history
…igned in an `__init_subclass__` or `__class_getitem__` method. These methods are implicitly class methods even though they are not decorated with `@classmethod`. This addresses microsoft/pylance-release#2781. (#9381)
  • Loading branch information
erictraut authored Nov 4, 2024
1 parent 3d9c95f commit 6fb940a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/pyright-internal/src/analyzer/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4033,9 +4033,10 @@ export class Binder extends ParseTreeWalker {
// To determine whether the first parameter of the method
// refers to the class or the instance, we need to apply
// some heuristics.
if (methodNode.d.name.d.value === '__new__') {
// The __new__ method is special. It acts as a classmethod even
// though it doesn't have a @classmethod decorator.
const implicitClassMethods = ['__new__', '__init_subclass__', '__class_getitem__'];
if (implicitClassMethods.includes(methodNode.d.name.d.value)) {
// Several methods are special. They act as class methods even
// though they don't have a @classmethod decorator.
isInstanceMember = false;
} else {
// Assume that it's an instance member unless we find
Expand Down
11 changes: 11 additions & 0 deletions packages/pyright-internal/src/tests/samples/initsubclass1.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,14 @@ class ClassH(ClassG):
# in the object.__init_subclass__ method.
class ClassI(a=3):
a: int


class ClassJ:
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
cls.custom_attribute = 9


class ClassJChild(ClassJ):
def __init__(self):
reveal_type(self.custom_attribute, expected_text="int")

0 comments on commit 6fb940a

Please sign in to comment.