5/10/2013 - 6:01 AM

Python class for masking dictionaries as objects

Python class for masking dictionaries as objects

# Generic data structure for mapping named arguments directly to properties
# More readable code than using dictionaries...
# Usage:
#   mystruct = Struct(value1 = "x", value2 = "y", value3 = "z")
#   print mystruct.value1
#    >> x

class Struct(object):
  def __init__(self, **entries):
		Struct.update(self, entries)

	def __repr__(self):
		return repr(self.__dict__)

	def __getattr__(self, name):
		if(name == '__dict__'):
			return self.__dict__
			return self.__dict__.get(name)

	def __setattr__(self, name, value):
		self.__dict__[name] = value

	def __getitem__(self, name):
		return self.__getattr__(name)

	def __setitem__(self, name, value):
		return self.__setattr__(name, value)

  # This method allows recursive mapping of Dictionaries to Structs
	def update(cls, self, entries):
		for k in self.__dict__.keys():
			if isinstance(self.__dict__[k], dict):
				self.__dict__[k] = Struct(** self.__dict__[k])
		return self