Sub topic 6
Defaults and the Class-Variable Conflict
This chapter assumes you know how instance and class attributes differ, and that you have seen __slots__ declared on a class. You should also know that slot names become descriptors on the class, which the previous chapter covered. Here you will see why the usual "default value as a class attribute" idiom breaks under __slots__, what error you get, and which patterns replace it.
The idiom that works without slots
In a regular class, a common way to give an attribute a default is to define it on the class. Attribute lookup on an instance checks the instance __dict__ first and then falls back to the class.
class Plain:
x = 0
p = Plain()
print(p.x)
p.x = 5
print(p.x, Plain.x, p.__dict__)The output is:
0
5 0 {'x': 5}Before the assignment, p.x finds nothing in the instance __dict__ and reads the class attribute. After the assignment, the instance has its own x that shadows the class value. The class value stays 0. Two storage locations share one name, and the lookup order decides which one wins.
Why slots cannot share a name with a class variable
A slotted class has no per-instance __dict__ to hold the shadowing value. The slot itself is a member descriptor stored in the class namespace under the slot's name, so the name x can appear only once in that namespace. If the class body also assigns x = 0, one entry would have to overwrite the other. Python refuses to choose and raises an error while the class is being created.
try:
class Bad:
__slots__ = ("x",)
x = 0
except ValueError as exc:
print("ValueError:", exc)The output is:
ValueError: 'x' in __slots__ conflicts with class variableThree details about this error are worth knowing.
- It is a
ValueErrorraised by the class statement, not by instance creation. A conflict shows up at import time, the first time the module is loaded. - It applies only to names listed in the same class's
__slots__. Class attributes with other names are allowed. - The order of statements in the class body does not matter. Putting
x = 0before or after__slots__fails the same way.
What an unset slot does
Without a class-level default, a slot that has not been assigned has no value. Reading it raises AttributeError, as you saw with member descriptors.
class Point:
__slots__ = ("x", "y")
p = Point()
print(getattr(p, "x", "missing"))
p.x = 1
print(getattr(p, "x", "missing"))
print(hasattr(p, "y"))The output is:
missing
1
Falsehasattr and getattr with a default both treat an unset slot as absent. That is why "the slot exists on the class" and "the instance has a value" are separate questions. Every slotted attribute you intend to read should be assigned before first use, which usually means in __init__.
Pattern 1: assign defaults in `__init__`
The standard replacement is to put the default in the initializer's signature or body. Each instance then fills its own slot at creation time.
class Account:
__slots__ = ("owner", "balance", "history")
def __init__(self, owner, balance=0, history=None):
self.owner = owner
self.balance = balance
self.history = [] if history is None else history
a = Account("ana")
b = Account("ben", balance=50)
a.history.append("opened")
print(a.balance, b.balance)
print(a.history, b.history)The output is:
0 50
['opened'] []The None sentinel for history matters. A signature such as history=[] creates one list when the function is defined, and every instance would share it. That bug exists in regular classes too. Slots make it easier to notice, because a class-level history = [] is not available as an alternative.
Immutable defaults such as numbers, strings, None, and tuples are safe to put directly in the signature. For mutable defaults, create a new object inside the body.
Pattern 2: class variables under different names
You can still have class-level values on a slotted class, provided their names are not in __slots__. They are shared by all instances and are read-only through an instance.
class Point:
__slots__ = ("x", "y")
DIMENSIONS = 2
def __init__(self, x=0, y=0):
self.x = x
self.y = y
p = Point()
print(p.DIMENSIONS, Point.DIMENSIONS)
try:
p.DIMENSIONS = 3
except AttributeError as exc:
print("AttributeError:", exc)
Point.DIMENSIONS = 3
print(p.DIMENSIONS)The output is:
2 2
AttributeError: 'Point' object attribute 'DIMENSIONS' is read-only
3In a regular class, p.DIMENSIONS = 3 would create an instance attribute that shadows the class one. In a slotted class there is nowhere to put it, so assignment through the instance fails. Assigning on the class changes the value for every instance. The exact wording of the message can differ between Python versions, but the exception type is AttributeError.
This pattern suits constants and configuration shared by all instances. It does not suit a default that individual instances may override.
Pattern 3: a fallback class attribute with a different name
If you want "use the class default unless the instance overrides it", you can keep the default under a private name and let __init__ choose between the two.
class Connection:
__slots__ = ("host", "timeout")
DEFAULT_TIMEOUT = 30
def __init__(self, host, timeout=None):
self.host = host
self.timeout = self.DEFAULT_TIMEOUT if timeout is None else timeout
print(Connection("db").timeout)
print(Connection("db", 5).timeout)
Connection.DEFAULT_TIMEOUT = 60
print(Connection("db").timeout)The output is:
30
5
60The default is read when the instance is created, not when the attribute is read. Instances made before a change to DEFAULT_TIMEOUT keep the value they were given. A regular class that relied on lookup fallback would behave differently, because it would see the new class value at read time for every instance that had not overridden it. If you depend on that live fallback behavior, slots are the wrong tool for that attribute.
Choosing a pattern
The flowchart shows the decision for one attribute.
| Approach | Name in `__slots__` | Per-instance override | Notes |
|---|---|---|---|
| `x = 0` in the class body | yes | not applicable | Raises `ValueError` at class creation |
| Default in `__init__` | yes | yes | Standard fix; assigned once per instance |
| `None` sentinel plus fresh object | yes | yes | Required for lists, dicts, and sets |
| Class constant under another name | no | no | Read-only via instance; change it on the class |
| Class default read in `__init__` | yes, for the stored copy | yes | Value is fixed at creation time |
Edge case: shadowing a parent's slot in a subclass
The conflict check looks only at the names in the class being created. A subclass can therefore define a class variable with the same name as a slot in its parent, and Python will not raise an error. The result is rarely what you want.
class Base:
__slots__ = ("x",)
class Child(Base):
__slots__ = ()
x = 0
c = Child()
print(c.x)
try:
c.x = 5
except AttributeError as exc:
print("AttributeError:", exc)The output is:
0
AttributeError: 'Child' object attribute 'x' is read-onlyLookup walks the class hierarchy in method resolution order and finds Child.x, a plain integer, before it reaches Base.x, the descriptor. The integer is not a descriptor with a setter, and Child instances have no __dict__, so there is nowhere to store a new value. The parent's slot memory is still allocated but unreachable by name. If the subclass had omitted __slots__, instances would have a __dict__ and assignment would succeed by storing into it. That is a plain-class pattern bolted onto a slotted base, and it gives up the memory savings.
Edge case: defaults that depend on other attributes
Because every slot is assigned in code, a default can be computed from other arguments. A class-level value could never do this.
class Rect:
__slots__ = ("width", "height", "area")
def __init__(self, width, height=None):
self.width = width
self.height = width if height is None else height
self.area = self.width * self.height
r = Rect(4)
print(r.width, r.height, r.area)The output is:
4 4 16Here area is stored, so it goes stale if width changes later. A property is better for derived values. A property named area cannot also be a slot, for the same name-conflict reason as above, so you would remove area from __slots__ and define it as a property.
Checklist for defaults in slotted classes
- List every name in
__slots__and make sure none of them is assigned in the class body. - Assign every slot in
__init__, or accept that reading it before assignment raisesAttributeError. - Use
Noneplus a fresh object for mutable defaults. - Keep shared constants under names that are not slots, and change them through the class.
- Do not reuse a parent's slot name as a class variable in a subclass.
The next chapter looks at how inheritance changes where attributes live. Later you will see dataclass(slots=True), which generates the slots for you and handles field defaults without hitting this conflict.
Exercise
This class fails with a ValueError when Python processes it: class Config with _slots = ("debug", "level"), a class-body line debug = False, and an init_ that sets self.level = 1. Explain why it fails and give a corrected version that keeps debug = False as the default but still lets each instance override it.
Show answer
The name debug is in _slots, so the slot descriptor is stored in the class namespace under "debug". The class-body assignment debug = False needs the same entry, which causes "ValueError: 'debug' in slots conflicts with class variable". Remove the class-body line and put the default in the initializer: def init_(self, debug=False, level=1): self.debug = debug; self.level = level. Each instance now stores its own debug value in its slot and can override it by passing an argument.
Exercise
A slotted class has _slots = ("items",) and the initializer def init_(self, items=[]): self.items = items. Two instances are created without arguments and one appends to its items. What does the other instance see, and how do you fix it?
Show answer
Both instances share the single list created when the function was defined, so the other instance sees the appended value. Slots do not change this. Use a sentinel: def _init_(self, items=None): self.items = [] if items is None else items. Each instance then gets its own list.
Exercise
A class Tag has _slots_ = ("name",) and a class variable VERSION = 1. What happens when you run Tag("a").VERSION = 2, and what is the way to change VERSION for all instances?
Show answer
The assignment raises AttributeError saying the attribute is read-only, because the instance has no _dict_ to hold a shadowing value and VERSION is not a slot. Assign on the class instead, with Tag.VERSION = 2, which changes the value that every instance reads.