A class which is designed to be easy to use when one needs a piece of data with a minimum of source required.
Usage:
shop = Data(owner="Homer", address="down the street", ice=Data(flavor="vanilla", amount=3))
print shop
Data:
owner = 'Homer'
ice = Data:
amount = 3
flavor = 'vanilla'
address = 'down the street'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 'module data provides class Data(object)'
from pprint import pformat
class Data(object):
"represents arbitrary data; provides functionality for displaying itself"\
" properly"
def __init__(self, *args, **kwargs):
if args:
self.args = args
for key, value in kwargs.items():
self.__dict__[key] = value
self.assert_data()
def __repr__(self):
if 'args' in self.__dict__:
args = map(repr, self.args)
else:
args = []
for key, value in self.__dict__.items():
if key != 'args':
args.append('%s=%r' % (key, value))
return self.__class__.__name__ + '(' + (', '.join(args)) + ')'
def __str__(self):
return self.formatted()
def assert_data(self):
"to be overridden for internal asserts after creation"
def stringify_arg(key, value, indent=None, variables=None):
if indent is None:
indent = ' '
if isinstance(value, Data):
if variables is None:
variables = {}
keys, values = variables.keys(), variables.values()
try:
i = values.index(value)
except ValueError:
return ('%s%s = %s' %
(indent, key,
value.formatted(indent=indent).
replace('\n', '\n%s%*s' % (indent, len(key)+3, ''))))
else:
return ('%s%s = %s' %
(indent, key, keys[i]))
else:
return ('%s%s = %s' %
(indent, key,
pformat(value).replace('\n',
'\n%s%*s' %
(indent, len(key)+3, ''))))
stringify_arg = staticmethod(stringify_arg)
def formatted(self, indent=None, variables=None):
result = [ self.__class__.__name__ + ':' ]
if 'args' in self.__dict__:
result.append(Data.stringify_arg('args', self.args,
indent=indent,
variables=variables))
for key, value in self.__dict__.items():
if key != 'args':
result.append(Data.stringify_arg(key, value,
indent=indent,
variables=variables))
return '\n'.join(result)
|