summaryrefslogtreecommitdiff
path: root/compat.py
diff options
context:
space:
mode:
authorPierre-Yves David <pierre-yves.david@logilab.fr>2008-06-24 11:59:16 +0200
committerPierre-Yves David <pierre-yves.david@logilab.fr>2008-06-24 11:59:16 +0200
commit6af087a3c32ac501f742d6dd1a74848175188d79 (patch)
tree370773b886753eaff75b1d28b820a6c432e955be /compat.py
parent156df98848bcc383fd126d7649d45410f975ecca (diff)
downloadlogilab-common-6af087a3c32ac501f742d6dd1a74848175188d79.tar.gz
compat: adds a max function taking 'key' as keyword argument
Diffstat (limited to 'compat.py')
-rw-r--r--compat.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/compat.py b/compat.py
index 7e98330..fc2b231 100644
--- a/compat.py
+++ b/compat.py
@@ -22,6 +22,8 @@ from __future__ import generators
from warnings import warn
+import __builtin__
+
from logilab.common.deprecation import class_renamed
try:
@@ -188,6 +190,44 @@ except NameError:
l2.reverse()
return l2
+try: #
+ max = max
+ max(("ab","cde"),key=len)
+except TypeError:
+ def max( *args, **kargs):
+ if len(args) == 0:
+ raise TypeError("max expected at least 1 arguments, got 0")
+ key= kargs.pop("key", None)
+ #default implementation
+ if key is None:
+ return __builtin__.max(*args,**kargs)
+
+ for karg in kargs:
+ raise TypeError("unexpected keyword argument %s for function max") % karg
+
+ if len(args) == 1:
+ items = iter(args[0])
+ else:
+ items = iter(args)
+
+ try:
+ best_item = items.next()
+ best_value = key(best_item)
+ except StopIteration:
+ raise ValueError("max() arg is an empty sequence")
+
+ for item in items:
+ value = key(item)
+ if value > best_value:
+ best_item = item
+ best_value = value
+
+ return best_item
+
+
+
+
+
# Python2.5 builtins
try:
any = any