Alternate Syntax for dictionary elements

Skip Montanaro skip at
Tue Jul 3 15:29:02 EDT 2001

    Gerson> dict = { 'type' : 'button', 'id': 32, 'name' : 'some name' }
    Gerson> if o.type == 'button':
    Gerson> 	# do something for objects of type button

    Gerson> Worthwile pursuit or total crap ?

How about:

    import UserDict

    class Dict(UserDict.UserDict):
	def __getattr__(self, name):
	    if name == "data":
		return self.__dict__['data']
		val =[name]
	    except KeyError:
		raise AttributeError, "object has no attribute %s" % name
	    return val

	def __setattr__(self, name, val):
	    if name == "data":
		self.__dict__['data'] = val
		self.__dict__['data'][name] = val

    def test():
	d = Dict()
	d['a'] = 1
	print d.a
	d.b = 1
	print d['b']
	    print d.c
	except AttributeError:
	    print "d.c does not exist, as expected"


Skip Montanaro (skip at

More information about the Python-list mailing list