Mutable mapping
A dictionary-like class validates keys and stores values.
Python · Module
__setitem__ implements assignment through subscription syntax such as obj[key] = value. It is used by mutable mappings and sequences to update, add, or replace stored elements.
Implement __setitem__ when an object should support assignment through square brackets. The method receives the key and value, then can replace an existing item or add a new one; its validation behavior should align with the corresponding lookup operation.
object.__setitem__(self, key, value)| Name | Type | Description |
|---|---|---|
self | object | The object whose item assignment is being implemented. |
key | object | The mapping key, sequence index, or slice being assigned. |
value | object | The replacement or newly assigned value. |
The documentation defines the operation and its arguments but does not specify a return value; implementations conventionally return None.
class Registry:
def __init__(self):
self._items = {}
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError("key must be a string")
self._items[key] = value
def __getitem__(self, key):
return self._items[key]
registry = Registry()
registry["port"] = 8080
print(registry["port"])Assignment with square brackets invokes the custom method, which validates the key and stores the value.
A dictionary-like class validates keys and stores values.
A custom list-like class replaces elements by index.
A container supports assigning a range of elements.
__setitem__ is the special method invoked for assignment written as self[key] = value. It receives the key and value and implements the object's storage or validation policy.
Follow-up: How should invalid keys be handled? Raise the same kinds of exceptions that the object's __getitem__ implementation raises for improper keys.
A mapping can use it to update an existing value or create a new key. A mutable sequence can use it when an element at a valid position may be replaced.
Follow-up: When should a class omit it? Omit it when keyed values cannot change and new keys cannot be added, or when sequence elements cannot be replaced.
Subscription syntax can also use slices, and __setitem__ participates in assigning to those slices. The method must therefore accept and interpret the key or slice according to the container's rules.
Follow-up: Which related methods complete container emulation? __getitem__ handles lookup and __delitem__ handles deletion; collections also provides MutableMapping as an abstract base class.
object.__getitem__object.__delitem__collections.MutableMapping