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

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, 14 lines
 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.

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

1 comment

Hamish Lawson 19 years, 7 months ago  # | flag

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.

Created by Tim Fitz on Sun, 15 Aug 2004 (PSF)
Python recipes (4591)
Tim Fitz's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks