[Guido's code] > unsorted = (1, 10, 2) > print MagicList.sorted(unsorted) > print MagicList(unsorted).sorted() > print SubClass.sorted(unsorted) > print SubClass(unsorted).sorted() Notwithstanding the "perverted" implementation, Alex's idea is absolutely wonderful and addresses a core usability issue with classmethods. If only in the C API, I would like to see just such a universalmethod alternative to classmethod. That would allow different behaviors to be assigned depending on how the method is called. Both list.sort() and dict.fromkeys() would benefit from it: class MagicDict(dict): def _class_fromkeys(cls, lst, value=True): "Make a new dict using keys from list and the given value" obj = cls() for elem in lst: obj[elem] = value return obj def _inst_fromkeys(self, lst, value=True): "Update an existing dict using keys from list and the given value" for elem in lst: self[elem] = value return self newfromkeys = MagicDescriptor(_class_fromkeys, _inst_fromkeys) print MagicDict.newfromkeys('abc') print MagicDict(a=1, d=2).newfromkeys('abc') An alternative implementation is to require only one underlying function and to have it differentiate the cases based on obj and cls: class MagicDict(dict): def newfromkeys(obj, cls, lst, value=True): if obj is None: obj = cls() for elem in lst: obj[elem] = value return obj newfromkeys = universalmethod(newfromkeys) Raymond Hettinger
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4