Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
PythonDoesWhat/pdw_009_attributedict.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
37 lines (30 sloc)
936 Bytes
This file contains 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
pdw_id = 9 | |
title = "Attributedict: dictionary whose keys are also attributes" | |
author = "Kurt" | |
pub_date = (2010, 12, 7, 16, 29) | |
tags = ('dict','attributes') | |
""" | |
No doubt Javascripters out there will find this construct pretty familiar. | |
""" | |
class attributedict(dict): | |
def __init__(self, *a, **kw): | |
self.__dict__ = self | |
dict.__init__(self, *a, **kw) | |
""" | |
attributedict is a dictionary whose keys are also accessible as object attributes. | |
This incredibly simple recipe is probably one of my favorites. For most intents | |
and purposes, it supplants the whole `bunch Python package <http://pypi.python.org/pypi/bunch>`_ | |
in four lines. | |
Let's see it in action: | |
>>> ad = attributedict() | |
>>> ad["one"] = 1 | |
>>> ad.one | |
1 | |
>>> ad.two = 2 | |
>>> ad["two"] | |
2 | |
>>> attributedict(three=3).three | |
3 | |
*Update*: we found `a similar recipe on ActiveState code`__. From 2005! | |
__ http://code.activestate.com/recipes/361668/ | |
""" |