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

ClassVarとは
Pythonのtyping.ClassVarは型修飾子(type qualifier)の1つで、属性がクラス変数であることを示し、インスタンス経由の属性への代入を型チェッカーのエラーにする。
仕様の提案文書は PEP 526 である。
- クラスの本体に型注釈と値を記述した属性は、実行時にはクラスの属性だが、型チェッカーはインスタンス変数のデフォルト値と判定し、インスタンス経由の代入をエラーにしない
ClassVarを指定すると、全インスタンスで共有する値へのインスタンス経由の代入が、実行前に型エラーとして検出される- dataclassでは、
ClassVarの属性は__init__の引数とフィールドから除外される - 型チェッカーは、クラス経由の代入を認め、インスタンス経由の代入をエラーにする
- 実行時には代入を禁止せず、インスタンス経由の代入はインスタンスに同名の属性を作成し、以後の参照ではその属性がクラス変数より優先される
クラス本体の型注釈はインスタンス変数のデフォルト値と判定される
型チェッカーの設定は標準とし、対象のPythonは3.13とする。
次のRegistryは、全インスタンスで共有する辞書をクラスの本体で定義した例である。
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 は、クラスの本体で初期化した属性について、インスタンス変数のデフォルト値か全インスタンスで共有するクラス変数かを型チェッカーは区別できない場合があることを示し、区別のためにClassVarを導入した。
PEP 526 で提案された、インスタンス変数を明示するInstanceVarは、インスタンス変数のほうが一般的で、一般的な用法を標準の扱いにすべきとして採用されなかった。
registryをClassVar[dict[str, int]]と宣言すると、属性そのものへのインスタンス経由の代入だけが型エラーになる。
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へのクラス経由の代入を認め、インスタンス経由の代入をエラーにする。
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を経由した代入は、サブクラスのインスタンスから呼ばれると サブクラスに同名の属性を作成し、基底のクラス変数を更新しない。
実行時の代入ではインスタンスの属性が優先される
ClassVarは実行時の代入を禁止しない。
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のフィールドは、インスタンスを経由した代入でも クラスの変数そのものが対象になる。
Pythonではインスタンス経由の代入がインスタンスの属性を作成し、クラス変数を更新しないので、この差による誤りを型チェッカーが検出する手段がClassVarである。
dataclassではClassVarの属性はフィールドとデフォルト値の制約の対象外になる
dataclassは、型がClassVarの属性をフィールドの対象外にする。
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になる。
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は、継承ではなく属性とメソッドの形でクラスの適合を判定する仕組みである。
型の仕様 は、Protocolのクラス変数とインスタンス変数をClassVarで区別すると定めている。
ClassVarを要求するProtocolにインスタンス変数のクラスを指定する場合と、その逆の場合は、どちらも型エラーになる。
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による構造的部分型 の判定では、属性の名前と型と同様に、クラス変数かインスタンス変数かの区別も一致が必要である。
サブクラスでの再宣言も同じ規則で、基底のクラス変数をインスタンス変数として再宣言する定義と、その逆の定義の両方がエラーになる。
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の型
型の仕様 は、型引数を省略したClassVarの型を代入した値から推論し、値もない場合はAnyとすると定めている。
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
型の仕様 は、入れ子の深さと無関係に、型引数に型変数を含むClassVarを誤りとする。
クラス変数は全インスタンスで共有されるので、インスタンスごとの型引数Tでは型が確定しない。
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の標準設定の場合、ジェネリクスのクラス のクラス変数に型変数を含めても検出されない。
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の禁止は 型の仕様 の規定で、どちらもクラス構文の型注釈がそれぞれキーとフィールドを定義するため、ClassVarを指定できない。
再代入を禁止するクラス変数とClassVarの使い分け
Finalは型修飾子(type qualifier)の1つで、変数や属性への再代入を型チェッカーのエラーにする。
型の仕様 では、通常のクラスの本体で初期化したFinalの属性は、ClassVarがなくてもクラス変数と判定される。
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の記事 のとおり、dataclassの本体のFinalはインスタンスのフィールドになり、変更不可のクラス変数にはClassVar[Final[int]]と記述する(Python 3.13以降)。
| 目的 | 記述の方法 |
|---|---|
| 全インスタンスで共有し、クラス経由で更新する値 | ClassVar[型] |
| インスタンスごとの値で、クラスにデフォルト値があるもの | ClassVarなしの型注釈 |
| 再代入を禁止するクラスの定数 | 通常のクラスではFinal、dataclassではClassVar[Final[型]] |
| dataclassのインスタンスごとのリストや辞書 | field(default_factory=list) |


