ActiveState Code

Recipe 299777: Simplified Mutable Instances


Often you want to just create an instance with nothing in it, then modify arbitrary values. According to the standard you should do: class Something: pass I propose the following better solution:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class MutableInstance(dict):
 def __init__(self):
  self.__dict__ = self

# This makes common tasks easier, not by much but conceptually it unifies things

Foo = MutableInstance()
Foo.x = 5
assert Foo['x'] == 5
Foo.y = 7
assert Foo.keys() == ['x', 'y']
assert Foo.values() == [5, 7]

# And now you can pass it to anything that wants a dictionary too.

Discussion

It's a suprisingly small but powerful change over just inheriting object (or nothing at all).

Comments

  1. 1. At 2:25 p.m. on 15 aug 2004, Hamish Lawson said:

    Care needed with allowing arbitrary attributes to be set. Consider Foo['keys'] == 5. Now you've clobbered your keys method. That's the reason why attribute access and dictionary lookup are separate mechanisms and have separate namespaces. Generally dictionaries should be used for arbitrary fields.

Sign in to comment