Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python descriptor for attribute-like access in dict subclasses
class dict_item:
"""
Create an attribute in a custom dict subclass that accesses
the dict value keyed by the attribute's name:
>>> class UserInfo(dict):
>>> name = dict_item()
>>> age = dict_item()
>>> user = UserInfo(name="John")
>>> print(user.name)
John
>>> user.age = 42
>>> user["color"] = "green"
>>> print(user)
{"name":"John", "age": 42, "color": "green"}
`user` acts as a normal dictionary, but the items under keys "name" and "age"
can be accessed as attributes too.
`dict_item` allows to easily create/prototype dict-based data structures
that have some predefined (but possibly missing) fields as attributes.
This makes the data structure more self-documenting than a regular dict
and helps avoiding key typo's (e.g. through code completion features in your
editor or IDE).
This class implements the descriptor protocol.
"""
def __set_name__(self, owner, name):
self.key = name
def __get__(self, instance, owner):
return instance[self.key]
def __set__(self, instance, value):
instance[self.key] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment