Alex Martelli wrote:
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).

Seems pretty reasonable -- the only thing I worry about is that classmethods and other attributes (e.g. properties) that are accessible from instances can lead to subtle bugs when a user accidentally initializes a Bunch object with the attributes of the same name, e.g.:


    b = Bunch(getDict=1)

where

    b.getDict()

now fails with something like "TypeError: 'int' object is not callable". (For another discussion about this problem, see [1]).

I don't know what the right solution is here... I wonder if I should write a classmethod-style descriptor that disallows the calling of a function from an instance? Or maybe I should just document that the classmethods should only be called from the class? Hmm...

How do you feel about getDict and setDict also being classmethods?


Steve

[1] http://mail.python.org/pipermail/python-dev/2005-January/051328.html
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to