Welcome, guest | Sign In | My Account | Store | Cart

Think of this as a JavaScript object. In JavaScript, the objects can be referenced by indexing (e.g. d[name]) or by directly using the dot (.) operator (e.g. d.name).

This is the same concept.

Note to Python 2.4 Users: You will need to change the "except KeyError as e:" line to "except KeyError, (e):".

Python, 9 lines
1
2
3
4
5
6
7
8
9
class SmartDict(dict):

	def __getattr__(self, name):
		try:
			return self[name]
		except KeyError as e:
			raise AttributeError(e)
	def __setattr__(self, name, value):
		self[name] = value

A very simple recipe, thanks to the ability to subclass built-in types. :)

It's very interesting because this recipe is smart enough not to let you overwrite the built-in methods.

>>> d = Dict(radius=10)
>>> d.radius
10
>>> d.copy = 10
>>> d.copy
<built-in method copy of Dict object at 0x02A056B8>
>>> d["copy"]
10
>>> d.copy()
{'copy': 10, 'radius': 10}
>>> d.fromkeys = lambda x: x * 2
>>> d.fromkeys([10], [10])
{10: [10]}
>>> d["fromkeys"](20)
40

2 comments

Alexandre Zani 13 years, 1 month ago  # | flag

I like it a lot. I would use "except KeyError, (e)" myself to be backwards compatible as far as v2.4 though.

Sunjay Varma (author) 13 years, 1 month ago  # | flag

I thought of that, but it breaks in 3.1... I'll put something in the original post about that.