[Python-Dev] Re: Guido's Magic Code was: inline sort option
Raymond Hettinger
python at rcn.com
Thu Oct 30 00:19:38 EST 2003
[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
More information about the Python-Dev
mailing list