empty classes as c structs?
Alex Martelli
aleaxit at yahoo.com
Sun Feb 6 15:36:06 EST 2005
Steven Bethard <steven.bethard at gmail.com> wrote:
> Hmm... interesting. This isn't the main intended use of
> Bunch/Struct/whatever, but it does seem like a useful thing to have...
> I wonder if it would be worth having, say, a staticmethod of Bunch that
> produced such a view, e.g.:
>
> class Bunch(object):
> ...
> @staticmethod
> def view(data):
> result = Bunch()
> result.__dict__ = data
> return result
>
> Then you could write your code as something like:
>
> gbls = Bunch.view(globals())
>
> I'm probably gonna need more feedback though from people though to know
> if this is a commonly desired use case...
Reasonably so, is my guess. Witness the dict.fromkeys classmethod -- it
gives you, on dict creation, the same kind of nice syntax sugar that
wrapping a dict in a bunch gives you for further getting and setting
(and with similar constraints: all keys must be identifiers and not
happen to clash with reserved words).
I think this ``view'' or however you call it should be a classmethod
too, for the same reason -- let someone handily subclass Bunch and still
get this creational pattern w/o extra work. Maybe a good factoring
could be something like:
class Bunch(object):
def __init__(self, *a, **k):
self.__dict__.update(*a, **k)
def getDict(self):
return self.__dict__
def setDict(self, adict):
self.__dict__ = adict
theDict = property(getDict, setDict, None,
"direct access to the instance dictionary"
)
@classmethod
def wrapDict(cls, adict, *a, **k):
result = cls.__new__(cls, *a, **k)
result.setDict(adict)
cls.__init__(result, *a, **k)
return result
I'm thinking of use cases where a subclass of Bunch might override
setDict (to do something else in addition to Bunch.setDict, e.g.
maintain some auxiliary data structure for example) -- structuring
wrapDict as a classmethod in a ``Template Method'' DP might minimize the
amount of work, and the intrusiveness, needed for the purpose. (I don't
have a real-life use case for such a subclass, but it seems to cost but
little to provide for it as a possibility anyway).
[[given the way property works, one would need extra indirectness in
getDict and setDict -- structuring THEM as Template Methods, too -- to
fully support such a subclass; but that's a well-known general issue
with property, and the cost of the extra indirection -- mostly in terms
of complication -- should probably not be borne here, it seems to me]]
Alex
More information about the Python-list
mailing list