Alternate Syntax for dictionary elements

Skip Montanaro skip at pobox.com
Tue Jul 3 21:29:02 CEST 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']
	    try:
		val = self.data[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
	    else:
		self.__dict__['data'][name] = val

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

    test()

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list