So I'm trying to get a prototype implementation of the 'generic object'
type. (I'm currently calling it 'bunch', but only because I can't
really think of anything better.) I'd like some feedback on what
methods it needs to support. Ideally I'd keep this as minimal as
possible...
Remember that the goal of the 'generic object' type is to allow the
programmer to make the design decision that attribute-style access is
more appropriate than []-style access. Given that, my feeling is that
the 'generic object' type should *not* support __(get|set|del) item__ ,
though I'm still undecided on __len__, __iter__, __contains__, items,
keys, values, etc.
Here's what I have currently:
import operator as _operator
class bunch(object):
def __init__(self, **kwds):
self.__dict__.u pdate(kwds)
def __eq__(self, other):
if not isinstance(othe r, bunch):
return False
attrs = set(self.__dict __)
if attrs != set(other.__dic t__):
return False
for attr in attrs:
if not getattr(self, attr) == getattr(other, attr):
return False
return True
def __repr__(self):
return '%s(%s)' % (self.__class__ .__name__,
', '.join('%s=%r' % (k, v)
for k, v in self.__dict__.i tems()))
def update(self, other):
self.__dict__.u pdate(other.__d ict__)
@classmethod
def frommapping(cls , mapping,
getkeys=iter, getitem=_operat or.getitem):
result = bunch()
for key in getkeys(mapping ):
value = getitem(mapping , key)
try:
value = bunch.frommappi ng(value)
except TypeError:
pass
setattr(result, key, value)
return result
type. (I'm currently calling it 'bunch', but only because I can't
really think of anything better.) I'd like some feedback on what
methods it needs to support. Ideally I'd keep this as minimal as
possible...
Remember that the goal of the 'generic object' type is to allow the
programmer to make the design decision that attribute-style access is
more appropriate than []-style access. Given that, my feeling is that
the 'generic object' type should *not* support __(get|set|del) item__ ,
though I'm still undecided on __len__, __iter__, __contains__, items,
keys, values, etc.
Here's what I have currently:
import operator as _operator
class bunch(object):
def __init__(self, **kwds):
self.__dict__.u pdate(kwds)
def __eq__(self, other):
if not isinstance(othe r, bunch):
return False
attrs = set(self.__dict __)
if attrs != set(other.__dic t__):
return False
for attr in attrs:
if not getattr(self, attr) == getattr(other, attr):
return False
return True
def __repr__(self):
return '%s(%s)' % (self.__class__ .__name__,
', '.join('%s=%r' % (k, v)
for k, v in self.__dict__.i tems()))
def update(self, other):
self.__dict__.u pdate(other.__d ict__)
@classmethod
def frommapping(cls , mapping,
getkeys=iter, getitem=_operat or.getitem):
result = bunch()
for key in getkeys(mapping ):
value = getitem(mapping , key)
try:
value = bunch.frommappi ng(value)
except TypeError:
pass
setattr(result, key, value)
return result
Comment