In this lesson, you will learn how to explicitly distinguish between data meant to be shared across all class instances and data unique to each specific object using ClassVar.
The Ambiguity of Class Attributes
When you define a variable inside a class body without an __init__ method, Python treats it as a class attribute. To a static type checker like mypy, however, a simple type annotation on a class attribute is ambiguous: does this represent a shared configuration, or is it just a default value for instance fields?
If you want to signal that a variable is intended to be a shared attribute (and should not be set on instances), you must use the typing.ClassVar annotation.
Practical Implementation
Consider a Configuration class where we want to keep track of a shared application name and a unique instance ID.
from typing import ClassVar
class AppSettings:
# This is a shared attribute for all instances
app_name: ClassVar[str] = "MyPythonApp"
# This is an instance field
user_id: int
def __init__(self, user_id: int):
self.user_id = user_id
# Usage
obj1 = AppSettings(101)
obj2 = AppSettings(202)
print(AppSettings.app_name) # Accessible via class
print(obj1.app_name) # Accessing via instance is allowed, but...
# obj1.app_name = "NewName" # Static checkers will flag this as an error!
Why Use ClassVar?
When you use ClassVar, you are explicitly telling your static type checker that app_name belongs to the class itself. If you accidentally attempt to write code that modifies this variable on an individual instance (like obj1.app_name = "..."), your type checker will catch this as a violation.
By using ClassVar, you clarify the architecture of your class: instance fields represent the "state" of a specific object, while ClassVar fields represent the "blueprint" or global settings shared by the entire class. This separation prevents logic errors where developers might mistakenly assume a shared constant is actually a unique instance variable.
Key Takeaway: Use ClassVar to wrap types for class-level attributes, ensuring that static type checkers can distinguish between shared constants and instance-specific fields.