Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
Created August 5, 2012 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenmcd/3260852 to your computer and use it in GitHub Desktop.
Save stephenmcd/3260852 to your computer and use it in GitHub Desktop.
Recursive force_unicode
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