Created
October 28, 2020 11:50
-
-
Save soxofaan/dc0417213c7e0b2f7f7cd586e685ceb3 to your computer and use it in GitHub Desktop.
Python descriptor for attribute-like access in dict subclasses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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