Sub topic 6
Defaults and the Class-Variable Conflict
This chapter assumes you know how to define classes with __init__, the difference between instance and class attributes, and how a slot descriptor sits on the class (covered in the previous chapters). Here you will see why a default value cannot share a name with a slot, and what to do instead.
The habit that breaks
In a regular class, a class attribute is a common way to give every instance a default value. Instances that never assign the attribute read the class's value.
class PlainCounter:
count = 0
c = PlainCounter()
print(c.count)
c.count = 5
print(c.count, PlainCounter.count)This works because reading c.count falls back to the class when the instance __dict__ has no count. Assigning c.count = 5 writes into the instance __dict__ and leaves the class value alone.
You might try the same thing with a slot:
class Bad:
__slots__ = ("x",)
x = 0Python raises this error while it creates the class:
ValueError: 'x' in __slots__ conflicts with class variableThe error appears at class creation, not when you make an instance. Importing the module is enough to trigger it.
Why the conflict exists
Each name in __slots__ becomes a member descriptor stored in the class namespace under that same name. The descriptor is what reads and writes the instance's slot storage. A class variable named x would need to occupy the same entry in the class namespace. Only one object can live there, so Python rejects the class instead of silently dropping one of them.
class Point:
__slots__ = ("x", "y")
print(type(Point.__dict__["x"]))The entry Point.__dict__["x"] is already taken by the descriptor. A default value has nowhere to go.
Setting defaults in `__init__`
The fix is to assign defaults when each instance is created. Use default arguments for values you want callers to override.
class Point:
__slots__ = ("x", "y")
def __init__(self, x=0, y=0):
self.x = x
self.y = y
print(Point().x, Point(3).x, Point(3, 4).y)Every instance now has all of its slots filled. That also avoids the unassigned-slot problem: reading a slot that was never set raises AttributeError, unlike a plain class where the class attribute would have been returned.
class Unset:
__slots__ = ("x",)
u = Unset()
print(hasattr(u, "x"))This prints False. The slot exists, but it holds nothing.
Two workarounds, and their limits
Sometimes you want a class-level default, for example a constant shared by all instances. You have two options.
- Use a different name for the class variable. Slot names and class-variable names only conflict when they are equal, so the two can coexist.
- Define a property that falls back to a default when the slot is empty.
class Config:
__slots__ = ("_timeout",)
DEFAULT_TIMEOUT = 30
@property
def timeout(self):
try:
return self._timeout
except AttributeError:
return self.DEFAULT_TIMEOUT
@timeout.setter
def timeout(self, value):
self._timeout = value
c = Config()
print(c.timeout)
c.timeout = 5
print(c.timeout)DEFAULT_TIMEOUT is an ordinary class variable and _timeout is the slot, so there is no clash. The property adds a function call to every read, so for hot paths, setting the value in __init__ is simpler and faster.
A shared mutable default is not a risk here
In plain classes, a class-level items = [] is shared by all instances, which is a well-known bug source. Slots remove that particular trap, because the conflict check stops you from writing it. For mutable defaults, create a fresh object in __init__:
class Bag:
__slots__ = ("items",)
def __init__(self):
self.items = []Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: 'x' in __slots__ conflicts with class variable` | A class variable has the same name as a slot | Move the default into `__init__` |
| `AttributeError` when reading a slot | The slot was never assigned | Assign every slot in `__init__` |
| Default shows on the class but not on instances | You expected the class value to act as a fallback | Slots do not fall back to class values, so set the value per instance |
Exercise
A class declares __slots__ = ("name", "tags") and also has the line tags = [] in its body. What happens when Python runs the class statement, and how would you give each instance its own empty list of tags?
Show answer
Python raises ValueError: 'tags' in __slots__ conflicts with class variable while creating the class. Remove the tags = [] line and assign self.tags = [] in __init__, so each instance gets its own list.
Exercise
Given class Box: __slots__ = ("size",), what does hasattr(Box(), "size") return, and why does it differ from a plain class that has size = 1 at class level?
Show answer
It returns False. The slot is an empty member descriptor until it is assigned, and reading it raises AttributeError. In the plain class, the lookup falls back to the class variable, so hasattr returns True.