Created
August 5, 2012 00:37
-
-
Save stephenmcd/3260852 to your computer and use it in GitHub Desktop.
Recursive force_unicode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.utils.encoding import force_unicode | |
from django.utils.functional import Promise | |
def deep_force_unicode(value): | |
""" | |
Recursively call force_unicode on value. | |
""" | |
if isinstance(value (list, tuple, set)): | |
value = type(value)(map(deep_force_unicode, value)) | |
elif isinstance(value, dict): | |
value = type(value)(map(deep_force_unicode, value.items())) | |
elif isinstance(value, Promise): | |
value = force_unicode(value) | |
return value | |
>>> from django.utils.translation import ugettext_lazy as _ | |
>>> x = {"a": _("foo"), _("b"): [1, 2, _("three"), set([_("baz"), _("bar")])]} | |
>>> x | |
{'a': <django.utils.functional.__proxy__ object at 0x101f8c3d0>, <django.utils.functional.__proxy__ object at 0x101f8c310>: [1, 2, <django.utils.functional.__proxy__ object at 0x101f8c390>, set([<django.utils.functional.__proxy__ object at 0x101f8c710>, <django.utils.functional.__proxy__ object at 0x101f8c410>])]} | |
>>> deep_force_unicode(x) | |
{'a': u'foo', u'b': [1, 2, u'three', set([u'bar', u'baz'])]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment