Skip to content

Commit

Permalink
added helper to work around py3 None sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
agroszer committed Feb 22, 2016
1 parent 8e5b74c commit 38199a2
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/z3c/form/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import zope.interface
import zope.contenttype
import zope.schema
from functools import total_ordering

from z3c.form import interfaces
from z3c.form.i18n import MessageFactory as _
Expand Down Expand Up @@ -66,6 +67,24 @@ def createId(name):
id = binascii.hexlify(name.encode('utf-8'))
return id.decode() if PY3 else id


@total_ordering
class MinType(object):
def __le__(self, other):
return True

def __eq__(self, other):
return (self is other)


def sortedNone(items):
if PY3:
Min = MinType()
return sorted(items, key=lambda x: Min if x is None else x)
else:
return sorted(items)


def createCSSId(name):
return str(''.join([
(char if char in _acceptableChars else
Expand Down
18 changes: 18 additions & 0 deletions src/z3c/form/util.txt
Original file line number Diff line number Diff line change
Expand Up @@ -557,3 +557,21 @@ Field and context is also overridable:

>>> util.changedWidget(widget, 'foo', field=IPerson['login'], context=p2)
False

`sortedNone()` function
------------------------

>>> util.sortedNone([None, 'a', 'b'])
[None, 'a', 'b']

>>> util.sortedNone([None, 1, 2])
[None, 1, 2]

>>> util.sortedNone([None, True, False])
[None, False, True]

>>> util.sortedNone([['true'], [], ['false']])
[[], ['false'], ['true']]

>>> util.sortedNone([('false',), ('true',), ()])
[(), ('false',), ('true',)]
2 changes: 1 addition & 1 deletion src/z3c/form/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def updateWidgets(self):
# always strings as keys, sorting an str(int/date) is lame
# also, newly added item should be the last...
try:
items = sorted(self.value)
items = util.sortedNone(self.value)
except:
# just in case it's impossible to sort don't fail
items = self.value
Expand Down

0 comments on commit 38199a2

Please sign in to comment.