[Python-Dev] Re: Guido's Magic Code was: inline sort option

Raymond Hettinger python at rcn.com
Thu Oct 30 00:49:53 EST 2003


[GvR]
> But your _inst_fromkeys mutates self!

That issue wasn't intrinsic to the proposal.
The implementation should have read:

class MagicDict(dict):
    def newfromkeys(obj, cls, lst, value=True):
        "Returns a new MagicDict with the keys in lst set to value"
        if obj is not None:
            cls = obj.__class__
        newobj = cls()
        for elem in lst:
            newobj[elem] = value
        return newobj
    newfromkeys = universalmethod(newfromkeys)



Universal methods give the method a way to handle the two
cases separately.  This provides both the capability to make
an instance from scratch or to copy it off an existing instance.

Your example was especially compelling:
  
    a = [3,2,1]
    print a.sorted()
    print list.sorted(a)


Raymond Hettinger




More information about the Python-Dev mailing list