# PythonのClassVarでクラス変数とインスタンス変数を型で区別する

## ClassVarとは

Pythonの`typing.ClassVar`は型修飾子（type qualifier）の1つで、属性がクラス変数であることを示し、インスタンス経由の属性への代入を型チェッカーのエラーにする。
仕様の提案文書は [PEP 526](https://peps.python.org/pep-0526/#class-and-instance-variable-annotations) である。

- クラスの本体に型注釈と値を記述した属性は、実行時にはクラスの属性だが、型チェッカーはインスタンス変数のデフォルト値と判定し、インスタンス経由の代入をエラーにしない
- `ClassVar`を指定すると、全インスタンスで共有する値へのインスタンス経由の代入が、実行前に型エラーとして検出される
- dataclassでは、`ClassVar`の属性は`__init__`の引数とフィールドから除外される
- 型チェッカーは、クラス経由の代入を認め、インスタンス経由の代入をエラーにする
- 実行時には代入を禁止せず、インスタンス経由の代入はインスタンスに同名の属性を作成し、以後の参照ではその属性がクラス変数より優先される

## クラス本体の型注釈はインスタンス変数のデフォルト値と判定される

型チェッカーの設定は標準とし、対象のPythonは3.13とする。

次の`Registry`は、全インスタンスで共有する辞書をクラスの本体で定義した例である。

```python
class Registry:
    # ClassVar なしの可変なデフォルト値をクラス本体に置く
    registry: dict[str, int] = {}


a = Registry()
b = Registry()
# インスタンス経由の変更が別インスタンスからも見える
a.registry["x"] = 1
print(a.registry, b.registry, a.registry is b.registry)
# インスタンス経由で辞書自体を代入し直す
a.registry = {"own": 2}
print(a.registry, b.registry, Registry.registry)
# mypy: エラーなし
# pyright: エラーなし
# 実行時の出力
# {'x': 1} {'x': 1} True
# {'own': 2} {'x': 1} {'x': 1}
```

`a.registry["x"] = 1`で変更した値は`b`からも参照でき、辞書は全インスタンスで共有されている。
一方、`a.registry = {"own": 2}`の代入は`a`だけに属性を作成し、以後の`a`はクラスの辞書と別の辞書を参照する。
型チェッカーは`registry`をデフォルト値つきのインスタンス変数と判定するので、この代入をエラーにしない。
[PEP 526](https://peps.python.org/pep-0526/#class-and-instance-variable-annotations) は、クラスの本体で初期化した属性について、インスタンス変数のデフォルト値か全インスタンスで共有するクラス変数かを型チェッカーは区別できない場合があることを示し、区別のために`ClassVar`を導入した。

PEP 526 で提案された、インスタンス変数を明示する`InstanceVar`は、[インスタンス変数のほうが一般的で、一般的な用法を標準の扱いにすべきとして採用されなかった](https://peps.python.org/pep-0526/#rejected-postponed-proposals)。

`registry`を`ClassVar[dict[str, int]]`と宣言すると、属性そのものへのインスタンス経由の代入だけが型エラーになる。

```python
from typing import ClassVar


class Registry:
    # 全インスタンスで共有する辞書を ClassVar で宣言する
    registry: ClassVar[dict[str, int]] = {}


a = Registry()
b = Registry()
# 辞書の中身の変更は属性への代入ではない
a.registry["x"] = 1
# 属性そのものへの代入はインスタンス経由では型エラーになる
a.registry = {"own": 2}
print(a.registry, b.registry, Registry.registry)
# mypy
# error: Cannot assign to class variable "registry" via instance  [misc]（14行目）
# pyright
# error: Cannot assign to attribute "registry" for class "Registry"（14行目）
# 実行時の出力: {'own': 2} {'x': 1} {'x': 1}
```

辞書の中身の変更（12行目）は属性への代入ではないので、どちらの型チェッカーもエラーにしない。

## インスタンス経由の代入は型エラーになり実行時には成功する

型チェッカーは、`ClassVar[int]`と宣言した`total`へのクラス経由の代入を認め、インスタンス経由の代入をエラーにする。

```python
from typing import ClassVar


class Counter:
    total: ClassVar[int] = 0
    name: str

    def __init__(self, name: str) -> None:
        self.name = name

    def bump_instance(self) -> None:
        # インスタンス経由でクラス変数へ加算する
        self.total += 1

    def bump_class(self) -> None:
        # 実際のクラスを経由してクラス変数へ加算する
        type(self).total += 1


c = Counter("one")
# インスタンス経由でクラス変数へ代入する
c.total = 1
# クラス経由でクラス変数へ代入する
Counter.total = 1
c.bump_instance()
c.bump_class()
print(c.name, c.total, Counter.total, c.__dict__)
# mypy
# error: Cannot assign to class variable "total" via instance  [misc]（13行目と22行目）
# pyright
# error: Cannot assign to attribute "total" for class "Counter*"（13行目）
# error: Cannot assign to attribute "total" for class "Counter"（22行目）
# 実行時の出力: one 2 2 {'name': 'one', 'total': 2}
```

メソッドの中の`self.total += 1`と、外からの`c.total = 1`が、両方の型チェッカーでエラーになる。
`Counter.total = 1`と`type(self).total += 1`のクラス経由の代入はエラーにならない。
メソッドの中で全サブクラスに共通のクラス変数を更新する場合は、`Counter.total`のようにクラスを名指しする。
`type(self)`や`@classmethod`の`cls`を経由した代入は、サブクラスのインスタンスから呼ばれると [サブクラスに同名の属性を作成し、基底のクラス変数を更新しない](https://docs.python.org/3/reference/datamodel.html#custom-classes)。

### 実行時の代入ではインスタンスの属性が優先される

`ClassVar`は実行時の代入を禁止しない。

```python
from typing import ClassVar, get_type_hints


class Counter:
    total: ClassVar[int] = 0


c = Counter()
# ClassVar は実行時のインスタンス代入を止めない
c.total = 1
print("instance", c.total, c.__dict__)
print("class", Counter.total)
# 型ヒントの取得後も ClassVar の修飾が残る
print("hints", get_type_hints(Counter))
print("annotations", Counter.__annotations__)
# mypy
# error: Cannot assign to class variable "total" via instance  [misc]（10行目）
# pyright
# error: Cannot assign to attribute "total" for class "Counter"（10行目）
# 実行時の出力
# instance 1 {'total': 1}
# class 0
# hints {'total': typing.ClassVar[int]}
# annotations {'total': typing.ClassVar[int]}
```

`c.total = 1`の実行後、`c`の`__dict__`には`total`が作成され、`Counter.total`は`0`のままである。
以後の`c.total`の参照の結果は、クラス変数ではなくインスタンスの属性の値である。

`get_type_hints`と`__annotations__`には`ClassVar[int]`が記録されているので、実行時の検証のライブラリは注釈から`ClassVar`を判別できる。

Javaの`static`のフィールドは、インスタンスを経由した代入でも [クラスの変数そのものが対象になる](https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.11.1)。
Pythonではインスタンス経由の代入がインスタンスの属性を作成し、クラス変数を更新しないので、この差による誤りを型チェッカーが検出する手段が`ClassVar`である。

## dataclassではClassVarの属性はフィールドとデフォルト値の制約の対象外になる

[dataclassは、型が`ClassVar`の属性をフィールドの対象外にする](https://docs.python.org/3/library/dataclasses.html#class-variables)。

```python
from dataclasses import dataclass, fields
from typing import ClassVar


@dataclass
class Point:
    x: int
    y: int
    # ClassVar の整数は初期化引数にもフィールドにもならない
    dimension: ClassVar[int] = 2
    # ClassVar のリストなら可変なデフォルト値も定義できる
    tags: ClassVar[list[str]] = []


point = Point(1, 2)
print(point, [field.name for field in fields(Point)], Point.tags)
try:
    # クラス変数の分まで位置引数を渡す
    Point(1, 2, 3)
except TypeError as error:
    print(type(error).__name__, str(error))
print(Point.dimension, point.tags is Point.tags)
# mypy
# error: Too many arguments for "Point"  [call-arg]（19行目）
# pyright
# error: Expected 2 positional arguments（19行目）
# 実行時の出力
# Point(x=1, y=2) ['x', 'y'] []
# TypeError Point.__init__() takes 3 positional arguments but 4 were given
# 2 True
```

`fields(Point)`の結果は`x`と`y`だけで、`dimension`と`tags`は`__init__`の引数にならない。
`Point(1, 2, 3)`は両方の型チェッカーでエラーになり、実行時も`TypeError`になる。

`ClassVar`の指定がない`list`のデフォルト値は、[dataclassの定義の時点で`ValueError`になる](https://docs.python.org/3/library/dataclasses.html#mutable-default-values)。

```python
from dataclasses import dataclass


@dataclass
class BadPoint:
    # ClassVar なしのリストデフォルト値は dataclass 定義時に拒否される
    tags: list[str] = []


print(BadPoint())
# mypy: エラーなし
# pyright: エラーなし
# 実行時: ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory
```

型チェッカーはこのデフォルト値をエラーにしない。
インスタンスごとのリストは`field(default_factory=list)`、全インスタンスで共有するリストは`ClassVar[list[str]]`で定義する。

## Protocolと継承ではクラス変数とインスタンス変数の区別も適合の条件になる

Protocolは、継承ではなく属性とメソッドの形でクラスの適合を判定する仕組みである。
[型の仕様](https://typing.python.org/en/latest/spec/protocol.html#protocol-members) は、Protocolのクラス変数とインスタンス変数を`ClassVar`で区別すると定めている。
`ClassVar`を要求するProtocolにインスタンス変数のクラスを指定する場合と、その逆の場合は、どちらも型エラーになる。

```python
from typing import ClassVar, Protocol


class NeedsClass(Protocol):
    x: ClassVar[int]


class HasInstance:
    def __init__(self) -> None:
        self.x: int = 1


class NeedsInstance(Protocol):
    x: int


class HasClass:
    x: ClassVar[int] = 2


# ClassVar を要求する Protocol にインスタンス変数を渡す
class_value: NeedsClass = HasInstance()
# インスタンス変数を要求する Protocol に ClassVar を渡す
instance_value: NeedsInstance = HasClass()
print(class_value.x, instance_value.x)
# mypy
# error: Incompatible types in assignment (expression has type "HasInstance", variable has type "NeedsClass")  [assignment]（22行目）
# note: Protocol member NeedsClass.x expected class variable, got instance variable
# error: Incompatible types in assignment (expression has type "HasClass", variable has type "NeedsInstance")  [assignment]（24行目）
# note: Protocol member NeedsInstance.x expected instance variable, got class variable
# pyright
# error: Type "HasInstance" is not assignable to declared type "NeedsClass"（22行目）
# error: Type "HasClass" is not assignable to declared type "NeedsInstance"（24行目）
# 実行時の出力: 1 2
```

[Protocolによる構造的部分型](https://kdot.co.jp/kdotdev/python-protocol-structural-subtyping) の判定では、属性の名前と型と同様に、クラス変数かインスタンス変数かの区別も一致が必要である。

サブクラスでの再宣言も同じ規則で、基底のクラス変数をインスタンス変数として再宣言する定義と、その逆の定義の両方がエラーになる。

```python
from typing import ClassVar


class ClassBase:
    x: ClassVar[int] = 1


class InstanceChild(ClassBase):
    # 基底のクラス変数をインスタンス変数として再宣言する
    x: int = 2


class InstanceBase:
    x: int = 3


class ClassChild(InstanceBase):
    # 基底のインスタンス変数をクラス変数として再宣言する
    x: ClassVar[int] = 4


print(InstanceChild().x, ClassChild().x)
# mypy
# error: Cannot override class variable (previously declared on base class "ClassBase") with instance variable  [misc]（10行目）
# error: Cannot override instance variable (previously declared on base class "InstanceBase") with class variable  [misc]（19行目）
# pyright
# error: Instance variable "x" overrides class variable of same name in class "ClassBase"（10行目）
# error: Class variable "x" overrides instance variable of same name in class "InstanceBase"（19行目）
# 実行時の出力: 2 4
```

## 型の推論と指定できない場所

### 型引数を省略したClassVarの型

[型の仕様](https://typing.python.org/en/latest/spec/class-compat.html#classvar) は、型引数を省略した`ClassVar`の型を代入した値から推論し、値もない場合は`Any`とすると定めている。

```python
from typing import ClassVar, reveal_type


class Bare:
    # 型引数なしで値を付けた ClassVar の型推論を見る
    y: ClassVar = 2
    # 型引数も値もない ClassVar の型推論を見る
    z: ClassVar


# 値を持つクラス変数の型を表示する
reveal_type(Bare.y)
try:
    # 注釈だけのクラス変数の型を表示する
    reveal_type(Bare.z)
except AttributeError as error:
    print(type(error).__name__, str(error))
print(Bare.y, Bare.__annotations__)
# mypy
# note: Revealed type is "int"（12行目）
# note: Revealed type is "Any"（15行目）
# pyright
# information: Type of "Bare.y" is "int"（12行目）
# information: Type of "Bare.z" is "Unknown"（15行目）
# 実行時の標準出力
# AttributeError type object 'Bare' has no attribute 'z'
# 2 {'y': typing.ClassVar, 'z': typing.ClassVar}
```

値のない`z`は、mypyでは`Any`、pyrightでは`Unknown`（型を推論できなかったことを示すpyrightの表示）になる。

`z: ClassVar`は注釈だけで値を作成しないので、実行時の`Bare.z`の参照は`AttributeError`になる。

### 型変数を含むClassVar

[型の仕様](https://typing.python.org/en/latest/spec/class-compat.html#classvar) は、入れ子の深さと無関係に、型引数に型変数を含む`ClassVar`を誤りとする。
クラス変数は全インスタンスで共有されるので、インスタンスごとの型引数`T`では型が確定しない。

```python
from typing import ClassVar, Generic, TypeVar

T = TypeVar("T")


class Box(Generic[T]):
    # クラス変数の型引数に型変数を直接使う
    value: ClassVar[T]
    # クラス変数の入れ子の型引数に型変数を使う
    values: ClassVar[list[T]] = []


print(Box.__annotations__)
# mypy: エラーなし
# pyright
# error: "ClassVar" type cannot include type variables（8行目と10行目）
# 実行時の出力: {'value': typing.ClassVar[~T], 'values': typing.ClassVar[list[~T]]}
```

この宣言は、pyrightではエラーになり、mypyの標準の設定ではエラーにならない。
mypyの標準設定の場合、[ジェネリクスのクラス](https://kdot.co.jp/kdotdev/python-typevar-variance) のクラス変数に型変数を含めても検出されない。

### ClassVarを指定できない場所

`ClassVar`の指定先は、クラスの本体の属性に限られる。

| 指定 | mypy | pyright |
|---|---|---|
| 関数の引数、関数の中の変数、モジュールの変数 | `ClassVar can only be used for assignments in class body` | `"ClassVar" is not allowed in this context` |
| 型引数の中`list[ClassVar[int]]` | `Invalid type: ClassVar nested inside other type` | 同上 |
| TypedDictのキー | `ClassVar[...] can't be used inside a TypedDict` | 同上 |
| NamedTupleのフィールド | `ClassVar[...] can't be used inside a NamedTuple` | 同上 |

TypedDictとNamedTupleの禁止は [型の仕様](https://typing.python.org/en/latest/spec/class-compat.html#classvar) の規定で、どちらもクラス構文の型注釈がそれぞれキーとフィールドを定義するため、`ClassVar`を指定できない。

## 再代入を禁止するクラス変数とClassVarの使い分け

`Final`は型修飾子（type qualifier）の1つで、変数や属性への再代入を型チェッカーのエラーにする。
[型の仕様](https://typing.python.org/en/latest/spec/qualifiers.html#semantics-and-examples) では、通常のクラスの本体で初期化した`Final`の属性は、`ClassVar`がなくてもクラス変数と判定される。

```python
from typing import Final, reveal_type


class Plain:
    # 通常クラス本体の Final と初期値の組合せを調べる
    x: Final = 1


plain = Plain()
reveal_type(Plain.x)
reveal_type(plain.x)
# インスタンス経由で Final の属性へ代入する
plain.x = 2
print(Plain.x, plain.x, plain.__dict__)
# mypy
# note: Revealed type is "Literal[1]?"（10行目と11行目）
# error: Cannot assign to final attribute "x"  [misc]（13行目）
# pyright
# information: Type of "Plain.x" is "Literal[1]"（10行目と11行目）
# error: Cannot assign to attribute "x" for class "Plain"（13行目）
# 実行時の標準出力: 1 2 {'x': 2}
```

[Finalの記事](https://kdot.co.jp/kdotdev/python-final-decorator) のとおり、dataclassの本体の`Final`はインスタンスのフィールドになり、変更不可のクラス変数には`ClassVar[Final[int]]`と記述する（Python 3.13以降）。

| 目的 | 記述の方法 |
|---|---|
| 全インスタンスで共有し、クラス経由で更新する値 | `ClassVar[型]` |
| インスタンスごとの値で、クラスにデフォルト値があるもの | `ClassVar`なしの型注釈 |
| 再代入を禁止するクラスの定数 | 通常のクラスでは`Final`、dataclassでは`ClassVar[Final[型]]` |
| dataclassのインスタンスごとのリストや辞書 | `field(default_factory=list)` |
